首页 > 解决方案 > 使用 JavaScript 将相似元素的 JSON 数组转换为嵌套数组

问题描述

假设我有以下 JSON 数组:

[
{
    "name": "x",
    "category": "y",
    "attributes": {
        "name": "a",
        "description": "b"
    }
},
{
    "name": "x",
    "category": "y",
    "attributes": {
        "name": "c",
        "description": "d"
    }
}
]

如何组合每个属性相同的元素,但将不同的属性添加到嵌套数组中:

[
{
    "name": "x",
    "category": "y",
    "attributes": [
     {
        "name": "a",
        "description": "b"
     },
     {
        "name": "c",
        "description": "d"
     }
  ]
}
]

更具体地说,任何不同的元素都应该附加到数组中——例如,如果名称为“c”的属性具有描述“b”,我仍然希望将整个属性附加到“属性”列表中。

通过广泛的搜索,我一直无法在 StackOverflow 上找到这个问题。我感谢您的帮助!

标签: javascriptarraysjson

解决方案


减少可以完成这项工作。这是一种方法

const myJson = [{
    "name": "x",
    "category": "y",
    "attributes": {
      "name": "a",
      "description": "b"
    }
  },
  {
    "name": "x",
    "category": "y",
    "attributes": {
      "name": "c",
      "description": "d"
    }
  }
]

const result = Object.values(
  myJson.reduce((acc, {
    name,
    category,
    attributes
  }) => (((acc[`${name}_${category}`] ??= {
    name,
    category,
    attributes: []
  }).attributes.push(attributes)), acc), {})
);
console.log(result)


推荐阅读