Tried to merge multiple json output in a single object using javascript but i do not know how to do it. I have one service.this service producing json data(like below the json format) on each api call.Finally i want to merge all json data in a single object.
product.component.ts:
public mergeAllproducts;
ngOnInit(){
this.mergeJson('collectionone');
this.mergeJson('collectiontwo');
this.mergeJson('collectionthree');
console.log(this.mergeAllproducts); //All json data in a single object
}
product.service.ts:
mergeJson(collection){
this.userService.getTableData(collection).subscribe(
res => {
//res is json data format
this.mergeAllproducts.push(res);
},
err => {
console.log(err);
}
);
}
}
Sample collection in a database is like below the json format.
[{
"pid": 1,
"product_name": "Mixed",
"product_weight": "1kg",
},{
"pid": 2,
"product_name": "Sweet",
"product_weight": "1kg",
},{
"pid": 3,
"product_name": "Fruit",
"product_weight": "500kg",
}]
mergeAllproductsas an empty array. In the api call, try to use thisthis.mergeAllproducts = [...this.mergeAllProducts, ...res]instead ofthis.mergeAllproducts.push(res);At the end of all the 3 calls, you would have one array with all objects inside it