29

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
givehug
  • 1,863
  • 1
  • 14
  • 19

2 Answers2

55

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
7

Using forEach:

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

Output:

 ["Nick", "Jordan", "Ramon"]
n-dru
  • 9,285
  • 2
  • 29
  • 42