我有给定格式的JSON:
{
"literature":
[
{
"category": "medical",
"title": "med title",
"abstract":"med abstract"
},
{
"category": "medical",
"title": "med title2",
"abstract":"med abstract2"
},
{
"category": "economics",
"title": "eco title",
"abstract":"eco abstract"
},
{
"category": "science",
"title": "sci title",
"abstract":"sci abstract"
}
]
}
期望输出:
{
"literature":
[
{
"medical":
[
{
"title": "med title",
"abstract":"med abstract"
},
{
"title": "med title2",
"abstract":"med abstract2"
}
]
},
{
"economics":
[
{
"title": "eco title",
"abstract":"eco abstract"
}
]
},
{
"science":
[
{
"title": "sci title",
"abstract":"sci abstract"
}
]
}
]
}
我会使用JSON.parse()
将JSON转换为javascript对象,然后修改该对象,将category属性作为键,并将数据合并到类似的键中,如上所示。自从最近三天以来我一直很震惊,请帮帮我
创建新对象并用于。。。的重写值
const response = {
"literature":
[
{
"category": "medical",
"title": "med title",
"abstract":"med abstract"
},
{
"category": "medical",
"title": "med title2",
"abstract":"med abstract2"
},
{
"category": "economics",
"title": "eco title",
"abstract":"eco abstract"
},
{
"category": "science",
"title": "sci title",
"abstract":"sci abstract"
}
]
}
function groupByCategory(items) {
const grouped = {}
for(const item of items) {
grouped[item.category] = grouped[item.category] || [];
const itemCopy = { ...item };
delete itemCopy.category
grouped[item.category].push(itemCopy)
}
console.log(grouped)
}
groupByCategory(response.literature)
您可以像下面的一样轻松地使用reduce
const rawData = {"literature":[{"category":"medical","title":"medtitle","abstract":"medabstract"},{"category":"medical","title":"medtitle2","abstract":"medabstract2"},{"category":"economics","title":"ecotitle","abstract":"ecoabstract"},{"category":"science","title":"scititle","abstract":"sciabstract"}]}
function formatData(data) {
return Object.keys(data).reduce((acc, key) => {
acc[key] = data[key].reduce((groups, {category, ...rest}) => {
if (!groups[category]) {
groups[category] = [];
}
groups[category].push(rest);
return groups;
}, {});
return acc;
}, {});
}
const result = formatData(rawData);
console.log(result)