首页 > 解决方案 > 如何在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",

}]

标签: javascripttypescriptangular8

解决方案


您可以使用扩展运算符合并三个集合,如下所示

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


推荐阅读