在我的 Angular 应用程序中,我的数据如下,
forEachArrayOne = [
{ id: 1, name: "userOne" },
{ id: 2, name: "userTwo" },
{ id: 3, name: "userThree" }
]
forEachArrayTwo = [
{ id: 1, name: "userFour" },
{ id: 2, name: "userFive" },
{ id: 3, name: "userSix" }
]
newObj: any = {};
ngOnInit() {
this.forEachArrayOne.forEach(element => {
this.newObj = { titleOne: "objectOne", dataOne: this.forEachArrayOne };
})
this.forEachArrayTwo.forEach(element => {
this.newObj = { titleTwo: "objectTwo", dataTwo: this.forEachArrayTwo };
})
console.log({ ...this.newObj, ...this.newObj });
}
在我的实际应用中,以上是结构,请帮助我以相同的方式达到预期的结果..
工作演示 https://stackblitz.com/edit/angular-gyched其结构如上。
这里 console.log(this.newObj)
给出最后一个对象,
titleTwo: "ObjectTwo",
dataTwo:
[
{ id: 1, name: "userFour" },
{ id: 2, name: "userFive" },
{ id: 3, name: "userSix" }
]
但我想将两者结合起来,并且需要与下面完全相同的结果..
{
titleOne: "objectOne",
dataOne:
[
{ id: 1, name: "userOne" },
{ id: 2, name: "userTwo" },
{ id: 3, name: "userThree" }
],
titleTwo: "ObjectTwo",
dataTwo:
[
{ id: 1, name: "userFour" },
{ id: 2, name: "userFive" },
{ id: 3, name: "userSix" }
]
}
请帮助我实现上述结果..如果我在任何地方错了,请纠正工作示例..
最佳答案
您将两个值都分配给 this.newObj
,因此它只会覆盖第一个对象。
此外,不需要循环。它不添加任何东西。
相反,您可以这样做:
this.newObjA = { titleOne: "objectOne", dataOne: this.forEachArrayOne };
this.newObjB = { titleTwo: "objectTwo", dataTwo: this.forEachArrayTwo };
console.log({ ...this.newObjA, ...this.newObjB });
**
编辑 **
在与您讨论了您的要求后,我可以看到不同的解决方案。
在调用componentData
之前,您需要确保您拥有完整的数据。为此,我们可以使用 forkJoin
将基准测试请求和项目请求加入到一个 Observable
中。然后我们可以订阅该 Observable 来获取两者的结果。
代码看起来像这样:
createComponent() {
let benchmarks, projects;
let form = this.productBenchMarkingForm[0];
if (form.benchmarking && form.project) {
benchmarks = form.benchmarking.filter(x => x.optionsUrl)
.map(element => this.getOptions(element));
projects = form.project.filter(x => x.optionsUrl)
.map(element => this.getOptions(element));
forkJoin(
forkJoin(benchmarks), // Join all the benchmark requests into 1 Observable
forkJoin(projects) // Join all the project requests into 1 Observable
).subscribe(res => {
this.componentData({ component: NgiProductComponent, inputs: { config: AppConfig, injectData: { action: "add", titleProject: "project", dataProject: this.productBenchMarkingForm[0] } } });
})
}
}
getOptions(element) {
return this.appService.getRest(element.optionsUrl).pipe(
map((res: any) => {
this.dataForOptions = res.data;
element.options = res.data;
return element;
})
)
}
<强> Here is an example in Stackblitz that logs the data to the console
关于javascript - 使用 typescript 合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53359869/