[英]method find javascript deep array object RN react native
这是我对象的一部分
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = fr;
const anyId = 3;
我不知道为什么执行以下操作:
const result = category[lang].list.find(item => item.id === anyId) console.log(result)
引发以下情况:
//未定义的category [lang] .list.find(item => item.id === anyId)不是函数,或者只是未定义
.map或.filter的结果相同
console.log(category)
返回错误 console.log(category[lang])
返回错误 console.log(category[lang].list)
返回错误 但其他任何东西都会返回错误。 这让我发疯,任何帮助将不胜感激。
使用const lang = "fr"
而不是const lang = fr
,因为fr
是未定义的变量,而"fr"
是字符串。 因此,您将获得category["fr"]
而不是category[fr]
。
const category = { fr: { list: [ {id: 1, label: 'coucou'}, {id: 2, label: 'moi'}, {id: 3, label: 'ici'}, {id: 4, label: 'maintenant'}, {id: 5, label: 'demain'}, ]}} const lang = "fr"; const anyId = 3; const result = category[lang].list.find(item => item.id === anyId) console.log(result)
您不希望category.fr
只是fr
,因为变量fr
不存在。
现在, lang
包含您的fr
的对象,你可以简单地做一个.find()
对lang.list
如下:
const category = { fr: { list: [ {id: 1, label: 'coucou'}, {id: 2, label: 'moi'}, {id: 3, label: 'ici'}, {id: 4, label: 'maintenant'}, {id: 5, label: 'demain'}, ]}} // Fill param from a variable, or anything, as long as it's a string: const param = 'fr'; // Use brackets here, as you want `category.fr` and not `category.param`: const lang = category[param]; //Or you can simply use: //const lang = category.fr; //If this is not a parameter, or user input const anyId = 3; console.log(lang); console.log(lang.list.find(item => item.id === anyId));
它在mdn沙箱上工作
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'ici'},
{id: 3, label: 'demain'},
{id: 4, label: 'matin'},
]
}
};
var lang ='fr';
var catID = 3;
console.log(lang);
console.log(catID);
console.log(category);
console.log(category[lang]);
console.log(category[lang].list);
var found = category[lang].list.find(function(element) {
return element.id === catID;
});
console.log(found.label); // demain
只需在回调函数中添加return,但它仍然无法在react-native上正常工作,因此问题仍然存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.