javascript - 使用 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 上找到这个问题。我感谢您的帮助!
解决方案
减少可以完成这项工作。这是一种方法
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)
推荐阅读
- c# - 通过 json api 端点上传 base64 编码文件遇到状态码 400
- java - 如何检查 .doc 文件中是否存在任何嵌入对象?
- go - 从另一个模块导入包
- python-3.x - 这在 python 中的表中如何工作,以不同的变量命名每一列和每一行,还有其他选择吗?
- php - php中的关联数组值+ =
- c++ - 出队实现删除所有记录而不是前记录?
- maven - 教科书中关于 Maven 的简单示例
- javascript - 在使用 express 路由器加载路由器模块时将参数传递给 require
- php - PHPMailer 在 null 上调用成员函数 isSMTP()
- apache-spark - 将pyspark相关的JAR包安装到Foundry