我建立了这个数组:
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
,但是怎么用?
答案 0 :(得分:4)
您可以减少用于平整属性的数组。
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);
答案 1 :(得分:2)
一起使用concat
和reduce
var a=[
{
title: 'something',
list: ['a', 'b', 'c', 'd']
},
{
title: 'dog',
list: ['aa']
},
{
title: 'cat',
list: ['aaa', 'b', 'cccc']
},
{
title: 'apple',
list: [],
}
];
console.log(a.reduce((acc,e)=>acc.concat(e.list),[]))
答案 2 :(得分:2)
您可以在concat
的空数组上使用map
并扩展语法...
。
const array = [{"title":"something","list":["a","b","c","d"]},{"title":"dog","list":["aa"]},{"title":"cat","list":["aaa","b","cccc"]},{"title":"apple","list":[]}]
const res = [].concat(...array.map(({list}) => list))
console.log(res)
答案 3 :(得分:1)
忘记MyClass, MyClass1, YourClass2, RepositoryClass,
和flatmap
。让事情简单明了。
reduce
答案 4 :(得分:0)
使用reduce
和...
(散布运算符)非常容易。
const array = [{
title: 'something',
list: ['a', 'b', 'c', 'd']
},
{
title: 'dog',
list: ['aa']
},
{
title: 'cat',
list: ['aaa', 'b', 'cccc']
},
{
title: 'apple',
list: [],
}
]
const result = array.reduce((accum, item) => {
return [...accum, ...item.list]
}, [])
console.log(result);