-1

I have an object that consists of iterable items (the keys are just datestrings). Some of these objects have more than one item.

I want to flatten every object so that I only keep objects with one dimension.

Basically, I want data to look like 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"
  }
];

I have tried mapping Object.keys:

function objToArr(obj: object): object[] {
  return Object.keys(obj).map(key => obj[key]);
}

But when I do it more than once (to cover the two dimensions) it returns this:

[
        {
          '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'
          }
        }
      ]
```
medicengonzo
  • 479
  • 1
  • 7
  • 23

1 Answers1

1

You could get there with a couple of Object.values calls. Something along these lines:

const expected = Object.values(data).map(v => Object.values(v)).flat()
ray
  • 26,557
  • 5
  • 28
  • 27