简体   繁体   中英

method find javascript deep array object RN react native

Here is a part of my object

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;

I don't know why when doing the following:

const result = category[lang].list.find(item => item.id === anyId) console.log(result)

Throws the following:

// undefined category[lang].list.find(item => item.id === anyId) is not a function, or just undefined

same result for .map or .filter

  • console.log(category) returns no error
  • console.log(category[lang]) returns no error
  • console.log(category[lang].list) returns no error

but anything else will return an error. It drives me crazy, any help will be highly appreciated.

Use const lang = "fr" instead of const lang = fr , because fr is an undefined variable but "fr" is a string. So you'll get category["fr"] instead of 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) 

You want category.fr not just fr , as the variable fr does not exist.

Now that lang contains your fr object, you can simply do a .find() on lang.list as below:

 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)); 

It works on mdn sandbox

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

just add a return inside the callback function, but it still doesn't work on react-native so the problem remains

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM