我有一个如下对象:
Response{
result:[{products:[o1,o2,o3]},{products:[o5,o7,o8]},{products:[o11,o12,o13]}]
}
如何使用函数式编程(过滤,映射,某些,化简等)创建所有产品对象o1,o2 ...的数组?
输出应为:
outArray = [o1,o2,o3,o5,o7,o8,o11,o12,o13]
答案 0 :(得分:3)
const products = [{products:[1,2,3]},{products:[5,7,8]},{products:[11,12,13]}];
const result = Array.prototype.concat.apply([], products.map(item => item.products));
console.log(result);
答案 1 :(得分:2)
使用Array#reduce,Array#push,destructuring和spread syntax:
const data = {result:[{products:['a','b','c']},{products:['a','b','c']},{products:['a','b','c']}]}
const res = data.result.reduce((a, {products}) => {
a.push(...products);
return a;
}, [])
console.log(res);
答案 2 :(得分:2)
较为冗长的替代方案,仍然使用map
和spread
运算符。
const init = [
{products: [1, 2, 3]},
{products: [5, 7, 8]},
{products: [11, 12, 13]}
];
const result = [].concat(...init.map(x => x.products));
console.log(result);
答案 3 :(得分:1)
您可以使用地图并结合在一起以获取欲望输出
let result =[{products:['o1','o2','o3']},{products:['o5','o7','o8']},{products:['o11','o12','o13']}];
let data = [result.map(function(o){ return o.products})].join(',').split(',');
console.log(data);
答案 4 :(得分:1)
使用Array.prototype.flatMap。
const data = [{products: ['o1','o2','o3']}, {products: ['o5','o7','o8']}, {products: ['o11','o12','o13']}];
console.log(data.flatMap(p => p.products));