我构建这个数组:
const array = [
{
title: 'something',
list: ['a', 'b', 'c', 'd']
},
{
title: 'dog',
list: ['aa']
},
{
title: 'cat',
list: ['aaa', 'b', 'cccc']
},
{
title: 'apple',
list: [],
}
]
我想要一个包含其他数组中所有值的数组,所以:
const res = ['a', 'b', 'c', 'd', 'aa', 'aaa', 'b', 'cccc']
我可以吗?我可以使用 concat
但如何使用呢?
最佳答案
您可以减少数组以展平属性。
const
array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
list = array.reduce((r, { list }) => [...r, ...list], []);
console.log(list);
或者可能即将到来flatMap
.
const
array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
list = array.flatMap(({ list }) => list);
console.log(list);
关于javascript - 在对象数组中连接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463977/