如何将嵌套对象“解包”为数组?

我有一个由可迭代项组成的对象(键只是日期字符串)。其中一些对象具有多个项目。


我想展平每个对象,以便只保留一个维度的对象。


基本上,我想data看起来像expected:


const data = {

//this datestring only has one item

  "1598989834745": {

    "219319571 ": {

      applicantCode: "goc2gp",

      carrera: "Trabajo Social",

      code: "219319571 "

    }

  },

//this one has two items

  "1598990166911": {

    "215576855": {

      applicantCode: "8e11532",

      carrera: "Médico Cirujano y Partero",

      code: "215576855"

    },

    "217831836": {

      applicantCode: "ybg14pd",

      carrera: "Trabajo Social",

      code: "217831836"

    }

  }

};


const expected = [

  {

    applicantCode: "goc2gp",

    carrera: "Trabajo Social",

    code: "219319571 "

  },

  {

    applicantCode: "8e11532",

    carrera: "Médico Cirujano y Partero",

    code: "215576855"

  },

  {

    applicantCode: "ybg14pd",

    carrera: "Trabajo Social",

    code: "217831836"

  }

];

我试过映射Object.keys:


function objToArr(obj: object): object[] {

  return Object.keys(obj).map(key => obj[key]);

}

但是当我不止一次这样做(覆盖两个维度)时,它会返回:


[

        {

          '219319571 ': {

            applicantCode: 'goc2gp',

            carrera: 'Trabajo Social',

            code: '219319571 '

          }

        },

        {

          '215576855': {

            applicantCode: '8e11532',

            carrera: 'Médico Cirujano y Partero',


            code: '215576855'

          },

          '217831836': {

            applicantCode: 'ybg14pd',

            carrera: 'Trabajo Social',

            code: '217831836'

          }

        }

      ]

```


喵喵时光机
浏览 85回答 1
1回答

慕婉清6462132

您可以通过几个Object.values调用到达那里。沿着这些线的东西:const expected = Object.values(data).map(v => Object.values(v)).flat()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript