亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數組中相同鍵的值合并到值數組

將數組中相同鍵的值合并到值數組

米脂 2022-12-29 13:52:16
我的數組如下所示const arr = [      {        "devices": "delete"      },      {        "devices": "update"      },      {        "devices": "read"      },      {        "alerts":"read"      }    ]我必須如下更改格式:const dict =  {"devices": ["update","read"],"alerts": ["read"]}有沒有最佳方法來實現這一目標?
查看完整描述

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);


查看完整回答
反對 回復 2022-12-29
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

是的。您需要創建一個空字典。如果字典中不存在項目或鍵,則在字典中創建鍵并分配一個空數組?,F在將項目插入其中。


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);


查看完整回答
反對 回復 2022-12-29
  • 2 回答
  • 0 關注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號