javascript - 如何在javascript中的单个对象中合并多个json数据
问题描述
尝试使用 javascript 将多个 json 输出合并到一个对象中,但我不知道该怎么做。我有一个服务。该服务在每个 api 调用上产生 json 数据(如下面的 json 格式)。最后我想将所有 json 数据合并到一个对象中。
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
}
产品.service.ts:
mergeJson(collection){
this.userService.getTableData(collection).subscribe(
res => {
//res is json data format
this.mergeAllproducts.push(res);
},
err => {
console.log(err);
}
);
}
}
数据库中的样本集合如下 json 格式。
[{
"pid": 1,
"product_name": "Mixed",
"product_weight": "1kg",
},{
"pid": 2,
"product_name": "Sweet",
"product_weight": "1kg",
},{
"pid": 3,
"product_name": "Fruit",
"product_weight": "500kg",
}]
解决方案
您可以使用扩展运算符合并三个集合,如下所示
mergeJson(collection){
this.userService.getTableData(collection).subscribe(
res => {
var collection = JSON.parse(res);
this.mergeAllproducts = [...this.mergeAllproducts , ...collection];
},
err => {
console.log(err);
}
);
}
}
[...Collection1,...Collection2,...Collection3]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
推荐阅读
- oracle - OAM 12c OAuth 访问令牌验证
- javascript - jQuery UI:一个元素中的两个方法
- string - 如何从 TypeScript 中的字符串中删除单引号
- android - 录制时将android视频拆分为多个文件
- mysql - 转换 InnoDB 失败。ERROR 1114 表已满
- python - 内核似乎已经死了。总是在我加载大文件时
- java - Android中的可选类
- android - Leanback BrowseFragment isShowingHeader() 方法行为
- javascript - 角度单元测试 TypeError:无法读取未定义的属性“订阅”
- c# - 使用 IOption<> 参数化的 Dotnet Core 默认构造函数调用