当我尝试在 find()
中使用 includes()
时,它不会超过 2 个项目。 JSON 文件有效。所以我想知道,既然这似乎不起作用,是否有更好的解决方案?
async function getTheRightObject(input){
let Obj = await aJSONFile.find(item => item.AnArray.includes(input));
console.log(Obj);
return Obj;
}
let userInput = "annother one";
getTheRightObject(userInput).then(function(output){
console.log(output);
}).catch(function (err) {
//Error things
});
JSON 类似:
[{
"Id": 1,
"Code": "586251af58422732b34344c340ba3",
"Input": ["official Name", "officialname", "oficial name", "officcial name"],
"Name": "Official Name",
"Flavor": "",
"Image": "https://123.com/image.png"
},
{
"Id": 2,
"Code": "597f723dceeca347a243422f9910e",
"Input": ["another one", "anotherone", "annother one", "another 1"],
"Name": "Another One",
"Flavor": "A bit of text",
"Image": "http://123.com/image2.png"
},
etc...
]
所以我想在这个 JSON 文件中搜索一个对象,该对象将用户的输入与 JSON 文件的对象 Input
相匹配,并返回 Name
。但这个解决方案似乎只适用于前 2/3 左右的项目。
编辑: 嗯,看来我在前两个对象中只有小写字符。在 json 文件中的其他对象中,我也使用了大写字符。
所以我的最终解决方案是;
- json 文件中的所有
object.Input = ['text1', 'text2', 'text3, 'etc']
现在均为小写 - 在输入上使用
toLowerCase()
。喜欢:
let Obj = wait aJSONFile.find(item => item.AnArray.includes(input.toLowerCase));
这适用于我的情况,因为我知道这些对象在我的情况下非常独特。在任何其他情况下(即当您期望多个对象时),您可以更好地使用此处的 Tiny Giant 或 varit05 的解决方案
最佳答案
给你!
find:find()方法返回数组中满足所提供的测试函数的第一个元素的值。
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
includes:includes()方法确定数组是否包含某个元素,并根据情况返回 true 或 false。
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
回答您的问题:
尝试使用 for
循环和 if
来获取对象数组中所需的数据。
希望对你有帮助!
关于javascript - 可以在 find() 中使用 include() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47875883/