2 回答
TA贡献1809条经验 获得超8个赞
你可以减少它!
const arr = [
{
"devices": "delete"
},
{
"devices": "update"
},
{
"devices": "read"
},
{
"alerts":"read"
}
]
let dict = arr.flatMap(el => Object.entries(el)).reduce((a,[key, value]) => {
if(key in a) {
a[key].push(value);
return a;
}
a[key] = [value];
return a;
},{})
console.log(dict);
TA贡献2065条经验 获得超13个赞
是的。您需要创建一个空字典。如果字典中不存在项目或键,则在字典中创建键并分配一个空数组。现在将项目插入其中。
const arr = [{
"devices": "delete"
},
{
"devices": "update"
},
{
"devices": "read"
},
{
"alerts": "read"
}
];
const dict = {};
arr.forEach(item => {
const key = Object.keys(item);
if (!dict[key]) {
dict[key] = [];
}
dict[key].push(item[key]);
})
console.log(dict);
添加回答
举报