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

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

JavaScript - 轉換對象,合并

JavaScript - 轉換對象,合并

慕田峪7331174 2022-09-02 17:22:27
我正在嘗試轉換下面的對象。我需要創建一個唯一位置的新數組,每個節點中都有位置和項對象。在JackOfAshes的幫助下,我能夠在這個筆會上走到一半。轉換此內容:const orig = [  {    item: {      name: "cat",      id: "ca_123"    },    location: {      name: "porch",      id: "por_123"    }  },  {    item: {      name: "dog",      id: "do_123"    },    location: {      name: "porch",      id: "por_123"    }  },  {    item: {      name: "snake",      id: "sn_123"    },    location: {      name: "forest",      id: "for_123"    }  },  {    item: {      name: "bird",      id: "bi_123"    },    location: {      name: "forest",      id: "for_123"    }  },  {    item: {      name: "beer",      id: "be_123"    },    location: {      name: "fridge",      id: "fri_123"    }  }];進入這個:const desired = [  {    name: "porch",    id: "por_123",    items: [      {        name: "cat",        id: "ca_123"      },      {        name: "dog",        id: "do_123"      }    ]  },  {    name: "forest",    id: "for_123",    items: [      {        name: "snake",        id: "sn_123"      },      {        name: "bird",        id: "bi_123"      }    ]  },  {    name: "fridge",    id: "fri_123",    items: [      {        name: "beer",        id: "be_123"      }    ]  }];
查看完整描述

1 回答

?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

你可以這樣做,或者使用reduce


const orig = [

  {

    item: {

      name: "cat",

      id: "ca_123"

    },

    location: {

      name: "porch",

      id: "por_123"

    }

  },

  {

    item: {

      name: "dog",

      id: "do_123"

    },

    location: {

      name: "porch",

      id: "por_123"

    }

  },

  {

    item: {

      name: "snake",

      id: "sn_123"

    },

    location: {

      name: "forest",

      id: "for_123"

    }

  },

  {

    item: {

      name: "bird",

      id: "bi_123"

    },

    location: {

      name: "forest",

      id: "for_123"

    }

  },

  {

    item: {

      name: "beer",

      id: "be_123"

    },

    location: {

      name: "fridge",

      id: "fri_123"

    }

  }

];


let formattedData = {}


orig.forEach(data=>{

  if(!formattedData[data.location.id]) formattedData[data.location.id]= {

    id: data.location.id,

    name: data.location.name,

    items:[]

  }

  formattedData[data.location.id].items.push(data.item)

})


const finalResponse = Object.entries(formattedData).map((e) => ( { ...e[1] } ));

console.log(finalResponse)


查看完整回答
反對 回復 2022-09-02
  • 1 回答
  • 0 關注
  • 80 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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