将对象数组转换为属性数组。

53

有没有一种简单的方法,使用filterparse或其他方式来转换如下的数组:

var someJsonArray = [
  {id: 0, name: "name", property: "value", otherproperties: "othervalues"},
  {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"},
  {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"}
];

将前一个数组中包含的对象的一个属性填充到一个简单的数组中,就像这样:

[0, 1, 2]

5
someJsonArray.map(function(o) { return o.id; }) 是什么意思?关于 map 的文档 - tforgione
我认为在回调函数中使用return甚至不起作用。 - E.K
1
@E.K 好的,那就试试看吧... - tforgione
1
我已经编辑了上面问题中的代码,以便开发人员更容易理解!哈哈。这只是一段示例代码,它并不能正常工作。 - Praveen Kumar Purushothaman
是的,我的错,因为示例中没有可访问的变量,所以忘记了引号。谢谢。 - Ellone
你也可以使用:Array.from(arrayLike, x => x.foo) - TechWisdom
4个回答

100

使用.map()函数:

finalArray = someJsonArray.map(function (obj) {
  return obj.id;
});

片段

var someJsonArray = [
  {id: 0, name: "name", property: "value", therproperties: "othervalues"},
  {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"},
  {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"}
];
var finalArray = someJsonArray.map(function (obj) {
  return obj.id;
});
console.log(finalArray);

上面的代码片段已被修改以使其正常工作。


21

一个更简单的例子(ES6及以后版本):

someJsonArray.map(({id}) => id)

这并不符合问题要求的工作方式。 - LGAP
@LGAP - 你能解释一下吗?我已经重新测试了它,与所要求的完全相符。 - coatesap
1
这个可以运行,但是为什么?第一个和第二个 id 的意义是什么? - Achmad Fathoni

1
你可以这样做:

var len = someJsonArray.length, output = [];
for(var i = 0; i < len; i++){
   output.push(someJsonArray[i].id)
}

console.log(output);

1
你可以这样做:

var arr = [];
for(var i=0; i<someJsonArray.length; i++) {
    arr.push(someJsonArray[i].id);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接