简体   繁体   English

如何获取对象数组并根据属性值创建数组?

[英]How to take an array of objects and create arrays based on property values?

I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value.我有一个对象数组,并试图获取这些对象中的值并将它们推送到基于相同属性值的数组中。 So for example.所以例如。

array = [
    {name: 'John', age: 12},
    {name: 'Lily', age: 22}
]

I have this array of objects and now I want to iterate through it and create arrays with all name values and age values.我有这个对象数组,现在我想遍历它并创建具有所有名称值和年龄值的数组。 The array also needs to be the same name as the values.该数组还需要与值同名。 So the result will be.所以结果会是。

name = ['John', 'Lily']

age = [12, 22]

How would I be able to do this?我怎么能做到这一点?

Just map over the array like so:只需像这样map数组:

 const array = [ {name: 'John', age: 12}, {name: 'Lily', age: 22} ] const name = array.map(e => e.name); const age = array.map(e => e.age); console.log(name); console.log(age);

EDIT编辑

If the array has dynamic objects, you can do this:如果数组有动态对象,你可以这样做:

 const array = [ {name: 'John', age: 12}, {name: 'Lily', age: 22} ]; for (var key in array[0]) { window[key] = array.map(e => e[key]); } console.log(name); console.log(age);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM