Iterating Array Of Objects In Javascript
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 },
Solution 1:
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);
}
);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution 2:
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.
Solution 3:
In plain JavaScript you can do this:
vararray = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
array.forEach(function(element, index) {
console.log(element.id+" "+element.caste);
});
The callback function is called with a third parameter, the array being traversed. For learn more!
So, you don't need to load jQuery library.
Greetings.
Solution 4:
vararray = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
var length = array.length;
for (var i = 0; i < length; i++) {
var obj = array[i];
var id = obj.id;
var caste = obj.caste;
}
Solution 5:
Arrow functions are modern these days
Using jquery $.each with arrow function
var array = [
{caste: "Banda", id: 4},
{caste: "Bestha", id: 6}
];
$.each(array, ( key, value ) => {
console.log('caste: ' + value.caste + ' | id: ' +value.id);
});
Using forEach with arrow function
array.forEach((item, index) => {
console.log('caste: ' + item.caste + ' | id: ' +item.id);
});
Using map with arrow function. Here map returns a new array
array.map((item, index) => {
console.log('caste: ' + item.caste + ' | id: ' +item.id);
});
Post a Comment for "Iterating Array Of Objects In Javascript"