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.
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]}`);
2
Answers
If you know the key and the index you need to access, you can just do
nested['40'][0].name
for instance.More generic:
See how you cannot do
nested.40
, as numeric values cannot be used with dot notation.You seem to be getting confused on what you’re working with here. You have an object first, so
const [, , {name}] = nested;
wouldn’t do anything. It’s an object, not an array.Same for
Object.values[40]
. With that one you have an array of objects, so there’s no object at that location to get values on. Anyway you’re usingObject.values
incorrectly there. You would do something likeObject.values(nested['40'][0])
.Try:
Also worth mentioning that although you are trying to work with numbers, those are used for arrays and numbers are coerced (changed) to strings here (when working with object keys). So it’s best to just work with strings directly to avoid confusion.