这是我的主数组的示例:
[
{
'data': [{'value': 'Red'}, {'value': 'Small'}, {'value': 'Good'}]
},
{
'data': [{'value': 'Black'}, {'value': 'Medium'}, {'value': 'Bad'}]
},
{
'data': [{'value': 'White'}, {'value': 'Large'}, {'value': 'Best'}]
}
]
我想要输出:
[
['Red', 'Black', 'White'], // all values from first index of data array
['Small', 'Medium', 'Large'], // all values from second index of data array
['Good', 'Bad', 'Best'] // all values from third index of data array
]
我尝试过使用 forEach
、for...in
、filter
等。但是我没有成功获得之前的输出。
最佳答案
您可以使用 reduce()
,然后在 reduce 循环中使用 forEach()
。在 forEach
循环中使用索引来确定要推送的数组。如果该索引处还没有值,请创建一个新数组并将其插入:
let data = [{'data': [{'value': 'Red'},{'value': 'Small'},{'value': 'Good'}]},{'data': [{'value': 'Black'},{'value': 'Medium'},{'value': 'Bad'}]},{'data': [{'value': 'White'},{'value': 'Large'},{'value': 'Best'}]}]
let arr = data.reduce((arr, item) => { // look at each item in the data array
item.data.forEach(({value}, index) => { // look at each item in the item.data array
(arr[index] || (arr[index] = [])).push(value) // create and array if necessary and push value into it
})
return arr
},[])
console.log(arr)
关于javascript - 通过每个索引对象值从多维数组创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906134/