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

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

合并復雜的多維數組

合并復雜的多維數組

Helenr 2021-03-30 17:19:15
在Javascript中,我創建了一個多維數組,但出于另一個目的,我需要對其進行轉換。所以我的數組是這樣的array [  0 => {    "ulStatic": [      0 => {        "day": "2019-03-30 18:30:00"        "id": "7"        "origin": "intentions"      }    ]    "ulDynamic": [      0 => {        "day": "2019-03-30 18:30:00"        "id": "275"        "origin": "obs"      }    ]    "ulCreatedDynamic": []  }  1 => {    "ulStatic": [      0 => {        "day": "2019-03-31 09:30:00"        "id": "8"        "origin": "intentions"      }    ]    "ulDynamic": []    "ulCreatedDynamic": []  }  2 => {    "ulStatic": []    "ulDynamic": []    "ulCreatedDynamic": [      0 => {        "day": "2019-04-03 19:30:00"        "id": "277"        "origin": "obs"      }    ]  }]我正在嘗試使用此數組:array [  0 => {    "day": "2019-03-30 18:30:00"    "elements": [      0 => {        "id": "7"        "origin": "intentions"      }      1 => {        "id": "275"        "origin": "obs"      }    ]  }  1 => {    "day": "2019-03-31 09:30:00"    "elements": [      0 => {        "id": "8"        "origin": "intentions"      }    ]  }  2 => {    "day": "2019-04-03 19:30:00"    "elements": [      0 => {        "id": "277"        "origin": "obs"      }    ]  }]我必須承認,我不知道從哪里開始。我在尋找map(),splice(),concat(),但這對我來說很混亂。您能幫我提出一些建議以實現這一目標嗎?
查看完整描述

3 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

day用reduce和對輸入進行分組,并返回對象值。


const inputAry = [{

    "ulStatic": [{

      "day": "2019-03-30 18:30:00",

      "id": "7",

      "origin": "intentions"

    }],

    "ulDynamic": [{

      "day": "2019-03-30 18:30:00",

      "id": "275",

      "origin": "obs"

    }],

    "ulCreatedDynamic": []

  },

  {

    "ulStatic": [{

      "day": "2019-03-31 09:30:00",

      "id": "8",

      "origin": "intentions",

    }],

    "ulDynamic": [],

    "ulCreatedDynamic": []

  },

  {

    "ulStatic": [],

    "ulDynamic": [],

    "ulCreatedDynamic": [{

      "day": "2019-04-03 19:30:00",

      "id": "277",

      "origin": "obs"

    }]

  }

];



const groupByDay = inputAry.reduce((group, statics) => {

  // flattens the statics array

  [].concat.apply([], Object.values(statics))

    .forEach(({

      day,

      id,

      origin

    }) => {

      // creates a dictionary entry with day as key, if already exist use the existing one or creates a new entry

      group[day] = group[day] || {

        day,

        elements: []

      };


      // push the id and origin to elements

      group[day].elements.push({

        id,

        origin

      });

    });


  return group;

}, {});


const expectedResult = Object.values(groupByDay);


console.log(expectedResult);


查看完整回答
反對 回復 2021-04-08
  • 3 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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