2 回答

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以減少它!
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貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
是的。您需要?jiǎng)?chuàng)建一個(gè)空字典。如果字典中不存在項(xiàng)目或鍵,則在字典中創(chuàng)建鍵并分配一個(gè)空數(shù)組?,F(xiàn)在將項(xiàng)目插入其中。
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);
添加回答
舉報(bào)