How to iterate over this javascript object?

Viewed 125

I have an object like below-

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};

I get individual values like

console.log(objResult[0].name); // xyz
console.log(objResult[1].name); // pqr

So when I iterate, I thought using for loop will do but objResult.length is giving value undefined

for(var i =0;i< objResult.length; i++){
console.log(objResult[i]);
}

Can u please help how to do it

7 Answers

Don't use an object, use an array instead:

var arrResult = [{name:"xyz"}, {name:"pqr"}, {name:"abc"}];

This will have a .length property and can be iterated normally with for … of loops.

If you actually got an object back, best convert it to an array:

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};
var arrResult = Object.assign([], objResult);

The ‘for...in’ construct allows you to iterate over all keys present on an object, even unowned.

The syntax is such: ‘for (const key in this) { }’

You can use Object.values or Object.entries and even Object.keys depending on what you need of the Object itself and then iterate over those results (as they are now an array) with either forEach or map.

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};

Object.values(objResult).forEach(({name}) => console.log(name));

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};

Object.entries(objResult).forEach(([k,{name}]) => console.log(name))

To access how many keys your object includes run the following:

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};
    lgth      = Object.keys(objResult).length;

console.log(lgth);

Why I did not use map but forEach instead in this case: map exists to create copies of existing values and map / transform them which is not what I want for a console.log.

Another way to do this is by using Object.keys() method.

It returns the list of keys in the object and then you can iterate over that list to get hold of the values.

for(let key in Object.keys(objResult)) {
    console.log(objResult[key]);
}

When using ES5 or later, you can map the object values within a single line of code like this:

Object.values(objResult).map(i => console.log(i));

Here you first create an array of the values with Object.values(objResult) and then iterate over every element using the map function.

If you do not want to use the map function you can iterate over the array with an loop (for example "for of" or "for in")

As specified by you, we can do that using for, but with some modifications.

var objResult = {0:{name:"xyz"}, 1:{name:"pqr"}, 2:{name:"abc"}};
for(let key in objResult) {
    let value = objResult[key].name;
    console.log(value);
}

Hope, this helps you

Related