Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested Objects into Arrays into an Object

I would need help to access the value of a key-value pair from an object that is itself nested into an array (several objects with 2 key-value pairs inside an array Several arrays into an object).

So for example, I would need to access only one of the names such as Max or Lucas…

I tried to access it but no luck… Any help would be much appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const nested = {
    40: [
        { hello: "1", name: "Max" },
        { hello: "2", name: "Julie" },
        { hello: "3", name: "Mark" },
        { hello: "4", name: "Isabella" },
    ],
    50: [
        { hello: "1", name: "William" },
        { hello: "2", name: "James" },
        { hello: "3", name: "Lucas" },
        { hello: "4", name: "John" },
    ],
};


// Here is what I tried but I didn't find any way to access a console.log that would return only a // single in the output.


const keysHello = Object.keys(nested);
console.log("keysHello", keysHello); // ['40', '50']

const values = Object.values(nested);
console.log("values", values); // [[{…}, {…}, {…}, {…}], [{…}, {…}, {…}, {…}])]

const keysValues = Object.entries(nested);
console.log("keysValues", keysValues); // [['40', [{…}, {…}, {…}, {…}]], ['50', [{…}, {…}, {…}, {…}]]

// The one below does not work
// const [, , {name}] = nested;
// console.log(`${Object.values[40]}`);

>Solution :

If you know the key and the index you need to access, you can just do nested['40'][0].name for instance.

More generic:

const nested = {
    40: [
        { hello: "1", name: "Max" },
        { hello: "2", name: "Julie" },
        { hello: "3", name: "Mark" },
        { hello: "4", name: "Isabella" },
    ],
    50: [
        { hello: "1", name: "William" },
        { hello: "2", name: "James" },
        { hello: "3", name: "Lucas" },
        { hello: "4", name: "John" },
    ],
};

const key = '40';
const index = 0;

const { name } = nested[key][index];

See how you cannot do nested.40, as numeric values cannot be used with dot notation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading