javascriptarraysobject

Accessing nested array within a object


I am stuck trying to get to the array within this object. It is showing them as [Object object] every time I try to print a value from the nested array.

This is the object:

{"current":true,
 "values_remaining":443,
 "color":"blue",
 "type":"1",
 "time":20444,
 "category":"story",
 "id":"kflaghe",
 "score":1270,

 "arr":[
        {"num":293,"person":"pera","val":"K3344"},
        {"num":407,"person":"perb","val":"B5637"},
        {"num":256,"person":"perc","val":"J4526"}
       ]
}

I was accessing the keys and values prior to the "arr" by using

for (const key in data) {
    console.log(`${key}: ${data[key]}`);
}

I found the above approach here: https://flexiple.com/javascript/loop-through-object-javascript

When I print everything up to the array it will show up properly as: score: 1270

But when it gets to the arr part, it prints as: arr: [object Object],[object Object],[object Object]

I researched and tried to access the array based on https://www.geeksforgeeks.org/what-is-json-array/

However, it is not recognizing the objects contained within the array. It prints [object Object],[object Object],[object Object] no matter what I do.

I tried to isolate that arr and one of the number values by using the following:

var arr= (`${data[key]}`);
var arrValue = arr[0];
console.log(arrValue.num);

it printed: undefined

How can I access these key value pairs contained within the array (the arr section)?


Solution

  • Nothing is wrong with how you're accessing your data. When you run code on Node, it just doesn't print out objects inside template strings.

    You can force node to print it out by stringifying an object. You can test your code with the following code.

    for (const key in data) {
        console.log(`${key}: ${JSON.stringify(data?.[key], null, 2)}`);
    }
    

    Also, you also mentioned that you are getting an undefined value when you try to isolate the array and access the num property inside it. That is most likely happening because you are trying to access the num property in one of your non-array properties. If you check the datatype of the value first, you should be able to do what you want.

    Below is how I would approach accessing both the array data and the non-array data in loop.

        for (const key in data) {
            const value = data[key]; // can be either an array or string or a number
    
            if (Array.isArray(value)) {
                for (const arrayItem of value) {
                    console.log(arrayItem)
                }
            }
    
            if (!Array.isArray(value)) {
                console.log(`${key}: ${data[key]}`);
            }
    
        }