Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate object in JavaScript? [duplicate]

I have this object. I want to iterate this object in JavaScript. How is this possible?

var dictionary = {     "data": [         {"id":"0","name":"ABC"},         {"id":"1","name":"DEF"}     ],     "images": [         {"id":"0","name":"PQR"},         {"id":"1","name":"xyz"}     ] }; 
like image 974
Piyush Avatar asked Mar 19 '13 10:03

Piyush


People also ask

How to copy properties of one object to another in JavaScript?

assign() The Object. assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Can you iterate over an object in JavaScript?

It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.


1 Answers

You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.

var data = dictionary.data;  for (var i in data) {      var id = data[i].id;      var name = data[i].name; } 

You can follow similar approach to iterate the image array.

like image 98
kavin Avatar answered Oct 26 '22 23:10

kavin