Lets say, I have an array of objects like this:
var students = [{
name: 'Nick',
achievements: 158,
points: 14730
}, {
name: 'Jordan',
achievements: '175',
points: '16375'
}, {
name: 'Ramon',
achievements: '55',
points: '2025'
}];
How do I loop through it (if i have to) so I get a list of certain key values. Lets say a list of all names.
Thanks.
Using forEach:
var a = [];
students.forEach(function(obj){
a.push(obj.name);
})
console.log(a);
Output:
["Nick", "Jordan", "Ramon"]
You can take Array.map(). This method returns an array with the elements from the callback returned. It expect that all elements return something. If not set, undefined will be returned.
var students = [{
name: 'Nick',
achievements: 158,
points: 14730
}, {
name: 'Jordan',
achievements: '175',
points: '16375'
}, {
name: 'Ramon',
achievements: '55',
points: '2025'
}];
var nameArray = students.map(function (el) { return el.name; });
document.getElementById('out').innerHTML = JSON.stringify(nameArray, null, 4);
<pre id="out"></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With