第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何從同級對象和過濾器元素數(shù)組中創(chuàng)建父子對象?

如何從同級對象和過濾器元素數(shù)組中創(chuàng)建父子對象?

慕碼人2483693 2022-09-02 16:13:01
我正在嘗試創(chuàng)建此對象:const data = [  {    "javascript": [      {        "product": "1234",      },      {        "product": "4321",      }    ]  },    {    "python": [      {         "product": "9876",      }    ]  }]這里的代碼片段是我試圖解析的原始對象:const myData = [  {    "category": "javascript",    "product": "1234"  },  {    "category": "javascript",    "product": "4321"  },  {    "category": "python",    "product": "9876"  },];const mountCategories = (data) => {  const categoriesObj = data.map(value => value.category).filter((value, index, a) => a.indexOf(value) === index)    const categorizedData = categoriesObj.map((value) => {    return {      value: data.map(value => {        return {          product: value.product,        }      })    }  });    return (    categorizedData  )}console.log(mountCategories(myData))我無法使類別鍵字符串正常工作。另外,我需要弄清楚如何正確過濾元素。
查看完整描述

1 回答

?
米脂

TA貢獻1836條經(jīng)驗 獲得超3個贊

你可以嘗試使用 array.reduce:


const myData = [

  {

    "category": "javascript",

    "product": "1234"

  },

  {

    "category": "javascript",

    "product": "4321"

  },

  {

    "category": "python",

    "product": "9876"

  },

];


let result = myData.reduce((acc,current) => {

   let prev = acc.find(doc => doc[current.category]);

   if(!prev){

      prev = { [current.category]: [] };

      acc.push(prev);

   }

   prev[current.category].push({product: current.product});

   

   return acc;

}, []);


console.log(result);


查看完整回答
反對 回復(fù) 2022-09-02
  • 1 回答
  • 0 關(guān)注
  • 61 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號