[英]Merge objects from two different type arrays
imagine that, we have two arrays.想象一下,我们有两个数组。 Each of the containing objects of different type.
每个包含不同类型的对象。 For example:
例如:
let first: Foo[] = [
{ a: 12, b: 'x', c: 0 },
{ a: 43, b: 'y', c: 0 }
];
let second: number[] = [11, 15];
I would like merge theirs objects in a way that I finally get one array looks like below:我想以一种最终得到一个数组的方式合并他们的对象,如下所示:
let first: Foo[] = [
{ a: 12, b: 'x', c: 11 },
{ a: 43, b: 'y', c: 15 }
];
As you can see I just want to assign value from the second array to c
property of object from first array.如您所见,我只想将第二个数组中的值分配给第一个数组中对象的
c
属性。
I hope that you understand my explanation of problem.我希望你能理解我对问题的解释。 I believe in your skills, guys!
我相信你的技能,伙计们!
you could zip
the two arrays into one,你可以将两个数组
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] });
});
As so often, Array.prototype.reduce
provides a good base for an approach like eg this one ...和
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; }
I think you should do it like this... Maybe not the best, but should work in you case :) This is very simple...我认为你应该这样做......也许不是最好的,但应该在你的情况下工作:)这很简单......
for(var i in second){
var elem = second[i];
first[i]['c'] = elem;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.