gpt4 book ai didi

javascript - Angular 2如何将对象数组放入另一个对象数组

转载 作者:行者123 更新时间:2023-11-30 08:21:00 26 4
gpt4 key购买 nike

所以我有 2 个数组(总是等于 index):

A: [
{name: Jhon1}
{name: Jhon2}
{name: Jhon3}
]

B: [
{lastName: Pom1}
{lastName: Pom2}
{lastName: Pom3}
]

合并后的预期结果:

A: [
{name: Jhon1, lastName: Pom1}
{name: Jhon2, lastName: Pom2}
{name: Jhon3, lastName: Pom3}
]

Concat 方法只是将整个数组合并成一个这样的:

  A: [
{name: Jhon1}
{name: Jhon2}
{name: Jhon3}
{lastName: Pom1}
{lastName: Pom2}
{lastName: Pom3}
]

我正在尝试的我自己的功能。下面有两个数组:this.pricesthis.search.favoriteItems,我想按照之前描述的方式合并:

showProducts(){
for(let i of this.localStorageArray){
let id = localStorage.getItem(i);
this.search.getProductsById(id).subscribe
((data: any) => {
this.prices.push(data.lowestPrices.Amazon);
this.search.favoriteItems.push(data);
//something here to merge this.prices and this.search
});

}
}

最佳答案

您可以将 .map() 与对象解构结合使用:

let arr1 = [{name: 'Jhon1'}, {name: 'Jhon2'}, {name: 'Jhon3'}],
arr2 = [{lastName: 'Pom1'}, {lastName: 'Pom2'}, {lastName: 'Pom3'}];

let zip = (a1, a2) => a1.map((o, i) => ({...o, ...a2[i]}));

console.log(zip(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - Angular 2如何将对象数组放入另一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com