Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a list of key values from array of objects - JavaScript [duplicate]

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.

like image 310
givehug Avatar asked Jun 29 '15 13:06

givehug


2 Answers

Using forEach:

var a = [];
students.forEach(function(obj){
    a.push(obj.name);
})
console.log(a);

Output:

 ["Nick", "Jordan", "Ramon"]
like image 41
n-dru Avatar answered Oct 12 '22 23:10

n-dru


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>
like image 71
Nina Scholz Avatar answered Oct 13 '22 00:10

Nina Scholz