我想从现有 JSON 构建一个新的 JSON
。源代码中的部分和标题我不再需要列出。名为“items”的新对象应该有一个项目数组。
最终的 JSON 应按属性“名称”排序,如下所示
{
"items": [
{
"id": 10000006,
"name": "Boah"
},
{
"id": 10000013,
"name": "Gut"
},
{
"id": 10000003,
"name": "Ipsum"
},
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000002,
"name": "Stet"
}
]
}
为了构建新的 JSON,我得到了这个来源:
{
"sections": [
{
"name": "FooBar",
"rubrics": [
{
"name": "Foo",
"items": [
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000002,
"name": "Stet"
},
{
"id": 10000003,
"name": "Ipsum"
}
]
},
{
"name": "Bar",
"items": [
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000006,
"name": "Boah"
}
]
}
]
},
{
"name": "BlahBloob",
"rubrics": [
{
"name": "Bla",
"items": [
{
"id": 10000013,
"name": "Gut"
}
]
},
{
"name": "Bloob",
"items": [
{
"id": 10000014,
"name": "Name"
},
{
"id": 10000015,
"name": "Lorem"
}
]
}
]
}
]
}
你觉得怎么样?我如何使用普通的 JavaScript
或 TypeScript
来做到这一点?
感谢您的阅读,并有时间回答我的问题。感谢您的提前回复。
最佳答案
给你。您只需迭代源的每个部分的每个标题即可获取项目。最后,按项目对项目列表进行排序,就完成了。
此示例使用 ES6 语法,但如果需要,可以轻松将其转换为 ES5。
function extractItems(source) {
const items = [];
for (const section of source.sections) {
for (const rubric of section.rubrics) {
items.push(...rubric.items);
}
}
items.sort((a, b) => a.name.localeCompare(b.name));
return { items };
}
关于javascript - 从现有 JSON 构建新 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39632521/