如何从对象数组中获取键值列表 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31117260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get a list of key values from array of objects - JavaScript
提问by givehug
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.
谢谢。
回答by Nina Scholz
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.
你可以带Array.map()
。此方法返回一个数组,其中包含返回的回调中的元素。它期望所有元素都返回一些东西。如果没有设置,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>
回答by n-dru
Using forEach
:
使用forEach
:
var a = [];
students.forEach(function(obj){
a.push(obj.name);
})
console.log(a);
Output:
输出:
["Nick", "Jordan", "Ramon"]