简体   繁体   English

从对象数组中的值组合 arrays?

[英]Combine arrays from values in array of objects?

I have an array that contains a bunch of objects:我有一个包含一堆对象的数组:

let sample = [
  {
    name: 'obj1',
    values: ["value1", "value2"]
  },
  {
    name: 'obj2',
    values: ["value3", "value4"]
  },
  {
    name: 'obj3',
    values: ["value5", "value6"]
  }
]

I need to combine all the arrays on the objects to end up with something like this:我需要将对象上的所有 arrays 组合起来,最终得到如下结果:

let outputArray = ["value1", "value2", "value3", "value4", "value5", "value6"]

Cant seem to find the best way to do this.似乎找不到最好的方法来做到这一点。 Thank you.谢谢你。

You could use Array.flatMap to first map each object to its values array, and then flatten the result:您可以使用Array.flatMap到第一个 map 每个 object 到它的values数组,然后将结果展平:

 let sample = [ { name: 'obj1', values: ["value1", "value2"] }, { name: 'obj2', values: ["value3", "value4"] }, { name: 'obj3', values: ["value5", "value6"] } ] let outputArray = sample.flatMap(o => o.values); console.log(outputArray);

In addition to Nick's answer, you can also use the reduce function for a wider range of support in different environments if you are not using tools like babel.除了 Nick 的回答,如果你不使用 babel 之类的工具,你还可以使用 reduce function 在不同环境中获得更广泛的支持。

 let sample = [ { name: 'obj1', values: ["value1", "value2"] }, { name: 'obj2', values: ["value3", "value4"] }, { name: 'obj3', values: ["value5", "value6"] } ] const result = sample.reduce((acc, item) => { return [...acc, ...item.values]; }, []); console.log(result);

You could use Array.reduce along with Array.concat :您可以将Array.reduceArray.concat一起使用:

 let sample = [ { name: 'obj1', values: ["value1", "value2"] }, { name: 'obj2', values: ["value3", "value4"] }, { name: 'obj3', values: ["value5", "value6"] } ]; let valuesArray = sample.reduce((a, b) => a.concat(b['values']), []); console.log(valuesArray);

I think what you want to employ is the array concat() method.我认为您要使用的是数组 concat() 方法。 This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.此方法不会更改现有的 arrays,但会返回一个新数组,其中包含连接的 arrays 的值。

My proposed solution:我提出的解决方案:

const outputArray = sample[0].values.concat(sample[1].values, sample[2].values);
let outputArray=[]  
sample.forEach(item=> { outputArray.push(item.values.map(val=> val)) })

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

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