how to get a list of key values from array of objects - JavaScript
48,052
Solution 1
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>
Solution 2
Using forEach
:
var a = [];
students.forEach(function(obj){
a.push(obj.name);
})
console.log(a);
Output:
["Nick", "Jordan", "Ramon"]
Author by
givehug
Updated on June 30, 2020Comments
-
givehug almost 4 years
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.