简体   繁体   English

使用 javascript 在 json 中组合对象

[英]Combine objects in a json using javascript

Having a JSON in this format:具有这种格式的 JSON:

[{
    name: "A",
    country: "X",
    countryID: "02",
    value: 15
  },
  {
    name: "A",
    country: "Y",
    countryID: "01",
    value: 25
  },
  {
    name: "B",
    country: "X",
    countryID: "02",
    value: 35
  },
  {
    name: "B",
    country: "Y",
    countryID: "01",
    value: 45
  }
]

how can I combine the objects by name , country , and countryID in Javascript to get the following JSON output?如何在 Javascript 中按namecountrycountryID组合对象以获得以下 JSON 输出?

[{
    country: "Y",
    countryID: "01",
    valueA: 25,
    valueB: 45
  },
  {
    country: "X",
    countryID: "02",
    valueA: 15,
    valueB: 35
  }
]

Using Array.prototype.reduce , you can group array items by country and countryID key-value pairs and store the result to the object values of that generated key as follows.使用Array.prototype.reduce ,您可以按countrycountryID键值对对数组项进行countryID ,并将结果存储到生成的键的对象值中,如下所示。

 const input = [{ name: "A", country: "X", countryID: "02", value: 15 }, { name: "A", country: "Y", countryID: "01", value: 25 }, { name: "B", country: "X", countryID: "02", value: 35 }, { name: "B", country: "Y", countryID: "01", value: 45 } ]; const groupBy = input.reduce((acc, cur) => { const key = `${cur.country}_${cur.countryID}`; acc[key] ? acc[key][`value${cur.name}`] = cur.value : acc[key] = { country: cur.country, countryID: cur.countryID, ['value' + cur.name]: cur.value }; return acc; }, {}); const output = Object.values(groupBy); console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM