javascript 访问对象数组的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8281824/
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
Accessing properties of an array of objects
提问by Dave
pretty basic question I think, but I couldn't find info on that.
我认为非常基本的问题,但我找不到相关信息。
Through d3 I parse a csv and each object look like this
通过 d3 我解析了一个 csv 并且每个对象看起来像这样
name: "whatever"
number: "52"
How can I access the array of all the properties "number" as an array without creating a new array and pushing each element?
如何在不创建新数组并推送每个元素的情况下将所有属性“数字”的数组作为数组访问?
采纳答案by Francois Nadeau
ES6 version:
ES6版本:
const numbers = objects.map( o => o.number );
Enjoy.
享受。
回答by Pointy
In JavaScript, you can't, because there is no such array. If you've got an array of objects, well, each object is its own precious little snowflake. You can of course transfer the "number" values to a new array, but it'd definitely be a new array.
在 JavaScript 中,你不能,因为没有这样的数组。如果您有一组对象,那么每个对象都是它自己珍贵的小雪花。您当然可以将“数字”值转移到一个新数组,但它肯定是一个新数组。
Some toolkits (Prototype and maybe Functional and Underscore) have a "pluck()" facility that's designed to do exactly what you want, but they too are forced to create new arrays.
一些工具包(Prototype,可能还有 Functional 和 Underscore)有一个“pluck()”工具,专门用来做你想做的事,但它们也被迫创建新的数组。
function pluck(array, property) {
var i, rv = [];
for (i = 0; i < array.length; ++i) {
rv[i] = array[i][property];
}
return rv;
}
Then:
然后:
var arrayOfNumbers = pluck(originalArray, "number");
回答by Jonathan M
for (i=0; i<myArrayOfObjects.length; i++) {
doWhatever(myArrayOfObjects[i].number);
}
回答by Colo Ghidini
If you are using lodash, you can do this:
如果你使用 lodash,你可以这样做:
var numbers = _.map(originalArray, 'number')
var numbers = _.map(originalArray, 'number')