Skip to content Skip to sidebar Skip to footer

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'},

Solution 1:

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)

Solution 2:

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 inputconst anyId = 3;

console.log(lang);

console.log(lang.list.find(item => item.id === anyId));

Post a Comment for "Method Find Javascript Deep Array Object Rn React Native"