[英]javascript - how do i flatten an array of json into an array of a particular json attributes?
So lets say i have an array like so 所以说我有一个像这样的数组
[
{name: "a", happyName: "bob" }
, {name: "b", happyName: "cow" }
, {name: "c", happyName: "moo" }
, {name: "d", happyName: "jen" }
]
What is the most efficient manner to flatten it to an array like so: 将其展平为数组的最有效方法是:
[ "a","b","c","d"]
(or alternatively to get only the happyName in the values instead - to be precise, i suppose, how would i flatten some given array into an array of some given named json attribute?) (或替代地,仅获取值中的happyName-确切地说,我想我如何将某个给定数组展平为某个给定命名json属性的数组?)
NB this is javascript only, no JQuery etc stuff please. 注意,这仅是javascript,请不要使用JQuery等。
This is a good use case for map()
: 这是
map()
好用例:
var names = theArray.map(function(item) {
return item.name;
});
var happyNames = theArray.map(function(item) {
return item.happyName;
});
If you have to do this a lot, it's quite easy to create a helper: 如果您需要做很多事情,创建一个助手很容易:
var names = values(theArray, 'name'),
happyNames = values(theArray, 'happyName');
function values(arr, attr) {
return arr.map(function(item) {
return item[attr];
});
}
var arr = [
{name: "a", happyName: "bob" }
, {name: "b", happyName: "cow" }
, {name: "c", happyName: "moo" }
, {name: "d", happyName: "jen" }
]
var names = arr.map(function(e) { return e.name } )
.map()
is a cool method, but keep in mind it's not compatible with legacy IE (<9). .map()
是一种很酷的方法,但是请记住,它与旧版IE(<9)不兼容。 If you want something that'll work everywhere, go for this: 如果您想要在任何地方都能使用的东西,请执行以下操作:
var arrayOfObjects = [
{name: "a", happyName: "bob" },
{name: "b", happyName: "cow" },
{name: "c", happyName: "moo" },
{name: "d", happyName: "jen" }
],
array = [],
i = 0,
len = arrayOfObjects.length;
for(;i<len;i++) {
array.push(arrayOfObjects[i].name);
}
// output => [ "a","b","c","d"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.