3 回答
TA贡献1827条经验 获得超4个赞
这使用Array.prototype.reduce和Array.prototype.forEach
{
const data = [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
const groupedData = data.reduce((carry, element) => {
element.tags.forEach(tag => {
carry[tag] = carry[tag] || []
carry[tag].push({...element})
})
return carry;
}, {})
console.log(groupedData)
}
TA贡献1842条经验 获得超21个赞
这里:
let arr = [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
];
let response = {};
for(let i of arr){
for(let j of i.tags){
let tags =[...i.tags]
if(response[j]){
response[j].push({...i , tags: tags})
} else{
response[j] = [{...i, tags: tags}];
}
}
}
console.log(response)
TA贡献1798条经验 获得超3个赞
输入数据:
const data = [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
];
const convertData = data.reduce((target, currentElem) => {
currentElem.tags.forEach(tag => {
target[tag] ? target[tag].push({...currentElem}) : target[tag] = [{...currentElem}];
});
return target;
}, {});
console.log(convertData);
添加回答
举报