为了账号安全,请及时绑定邮箱和手机立即绑定

合并复杂的多维数组

合并复杂的多维数组

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 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信