我的对象输入数组是这样的,我有一个如下所示的输入数组:
[{"id": 657, "name": "Amadeus Basin", "contenttype": "province"}
{"id": 1173, "name": "Amazonas Basin", "contenttype": "province"}
{"id": 373, "name": "American Samoa", "contenttype": "countries"}
{"id": 1, "name": "Samoa", "contenttype": "marine"}
{"id": 796, "name": "Amhara", "contenttype": "province"}]
我想实现的是:
[
{
"contenttype": "province",
"content" : [
{
"id": 657,
"name": "Amadeus Basin"
},
{
"id": 1173,
"name": "Amazonas Basin"
},
{
"id": 796,
"name": "Amhara"
}
]
}, {
"contenttype": "countries",
"content": [
{
"id": 373,
"name" : "American Samoa"
}
]
},
{
"contenttype": "countries",
"content": [
{
"id": 1,
"name" : "Samoa"
}
]
}
]
根据一个值拆分数组中的对象,并在这些新创建的对象中创建相同对象的子数组。使用 lodash 也会很好。
您可以使用reduce
函数迭代每个项目,然后检查它是否存在于数组中,如果没有找到,则添加新的,如果找到 - 推入它
const data = [{"id": 657, "name": "Amadeus Basin", "contenttype": "province"},
{"id": 1173, "name": "Amazonas Basin", "contenttype": "province"},
{"id": 373, "name": "American Samoa", "contenttype": "countries"},
{"id": 1, "name": "Samoa", "contenttype": "marine"},
{"id": 796, "name": "Amhara", "contenttype": "province"}];
const grouped = data.reduce((acc, item) => {
const found = acc.find(i => i.contenttype === item.contenttype);
const content = {id: item.id, name: item.name};
if(found) {
found.content.push(content);
} else {
acc.push({contenttype: item.contenttype, content: [content] })
}
return acc;
}, []);
console.log(grouped);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句