How to get a list of key values ​​from an array of objects - JavaScript

Let's 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 go through it (if needed) so I get a list of specific key values. List of all names.

Thank.

+3


source to share


2 answers


You can take Array.map()

. This method returns an array with the elements of the return callback. It expects all elements to return something. Returns if not specified undefined

.



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>
      

Run codeHide result


+7


source


Usage forEach

:

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

      



Output:

 ["Nick", "Jordan", "Ramon"]

      

0


source







All Articles