Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Array of Objects in javascript

Tags:

I am having an array that consists the objects with a key, value how can we iterate each object for caste and id.

[     Object {         caste = "Banda",         id = 4     },     Object {         caste = "Bestha",          id = 6     } ] 
like image 486
sasi Avatar asked Apr 26 '13 10:04

sasi


People also ask

How do I iterate an array of objects in Node JS?

forEach() is an array function from Node. js that is used to iterate over items in a given array. Parameter: This function takes a function (which is to be executed) as a parameter. Return type: The function returns array element after iteration.

Can we use for loop to iterate an object in JavaScript?

Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes.


2 Answers

Using jQuery.each():

var array = [     {caste: "Banda", id: 4},     {caste: "Bestha", id: 6}  ];        $.each(array, function( key, value ) {    console.log('caste: ' + value.caste + ' | id: ' +value.id);  }    );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 131
RRikesh Avatar answered Oct 19 '22 22:10

RRikesh


Example code:

var list = [      { caste:"Banda",id:4},      { caste:"Bestha",id:6},  ];        for (var i=0; i<list.length; i++) {      console.log(list[i].caste);  }

It's just an array, so, iterate over it as always.

like image 20
Salvatorelab Avatar answered Oct 19 '22 22:10

Salvatorelab