[英]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.