2017-02-11 14 views
0

我有對象的數組說:如何讓2個元素出1的地圖期間Lodash

let array = [{x: 3}, {x: 4}, {x: 5}]; 

我要地圖它和每個現有的後面添加新元素。因此,要保持它的簡單,我想獲得:

let mappedArray = [{x: 3}, {y: 3}, {x: 4}, {y: 4}, {x: 5}, {y: 5}]; 

它可以與扁平化這樣進行:

let mappedAray = _(array) 
    .map(obj => {return [obj, {y: obj.x}]}) 
    .flatten() 
    .value(); 

但我不知道,也許還有一個更優雅的解決方案。某種我不知道的oneliner方法。

回答

2

您可以使用純平JavaScript的reduce()

let array = [{x: 3}, {x: 4}, {x: 5}]; 
 
var result = array.reduce((r, e) => (r.push(e, {y: e.x}), r), []) 
 

 
console.log(result)

0

使用Array.prototype.forEach()Array.prototype.push()功能的解決方案:

var arr = [{x: 3}, {x: 4}, {x: 5}], result = []; 
 

 
arr.forEach(function(o){ result.push(o, {y: o.x}) });  
 
console.log(result);

0

不能你只需要使用Object.assign?

let array = [{x: 3}, {x: 4}, {x: 5}]; 
 
let mappedArray = [{x: 3}, {y: 3}, {x: 4}, {y: 4}, {x: 5}, {y: 5}]; 
 

 
const mapArray = (a, b) => Object.assign([],a,b); 
 

 
console.log(mapArray(array,mappedArray));

相關問題