![](/img/trans.png)
[英]Merge objects with corresponding key values from two different arrays of objects
[英]Merge objects from two different type arrays
想象一下,我們有兩個數組。 每個包含不同類型的對象。 例如:
let first: Foo[] = [
{ a: 12, b: 'x', c: 0 },
{ a: 43, b: 'y', c: 0 }
];
let second: number[] = [11, 15];
我想以一種最終得到一個數組的方式合並他們的對象,如下所示:
let first: Foo[] = [
{ a: 12, b: 'x', c: 11 },
{ a: 43, b: 'y', c: 15 }
];
如您所見,我只想將第二個數組中的值分配給第一個數組中對象的c
屬性。
我希望你能理解我對問題的解釋。 我相信你的技能,伙計們!
你可以將兩個數組zip
成一個,
const first: Foo[] = [
{ a: 12, b: 'x', c: 0 },
{ a: 43, b: 'y', c: 0 }
];
const second: number[] = [11, 15];
const result: Foo[] = first.map((e, i) => {
return <Foo>Object.assign({}, e, { c: second[i] });
});
和Array.prototype.reduce
, Array.prototype.reduce
為類似這樣的方法提供了一個很好的基礎......
var listOfItems = [ { a: 12, b: 'x', c: 0 }, { a: 43, b: 'y', c: 0 } ]; var listOfValues = [11, 15]; function reassignValueToGivenKey(collector, item, idx) { item = Object.assign({}, item); // do not mutate original reference. item[collector.key] = collector.valueList[idx]; // reassign value. collector.itemList.push(item); // collect processed items separately. return collector; } var result = listOfItems.reduce(reassignValueToGivenKey, { key: 'c', valueList: listOfValues, itemList: [] }).itemList; console.log('listOfItems : ', listOfItems); console.log('result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
我認為你應該這樣做......也許不是最好的,但應該在你的情況下工作:)這很簡單......
for(var i in second){
var elem = second[i];
first[i]['c'] = elem;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.