Home > Mobile >  convert object into array of objects with additional properties in it
convert object into array of objects with additional properties in it

Time:09-16

I have below code of data. It is an object and each key has a date to it. There are properties Open and Closed within it. If Closed is 0, then that property is not present.

let data = {
          "2021-09-06": {
            "Open": 24
          },
          "2021-09-07": {
            "Open": 80,
            "Closed": 14
          },
        }

I want to achieve the following

let res = [
          { "date": "2021-09-06", "Open": 24, "Closed": 0 },
          { "date": "2021-09-07", "Open": 80, "Closed": 14 },
        ]

Can someone please let me know how to achieve this. I have tried this way but i dont get date property within the object as i want.

Object.entries(data).map((e) => ( { [e[0]]: e[1] } ));

CodePudding user response:

You're on the right track.

Object.entries() returns an array of [key, value] tuples, so in your case each entry will look something like ['2021-09-06', { Open: 24,}].

You can destructure this passed tuple in the map() call which makes it more descriptive.

Object.entries(data).map(([date, value]) => ...

You can then use shorthand asignment to create the date property, declare a default Closed: 0 property, and then use spread syntax to apply the existing properties of the value object which will overwrite the Closed property if it exists in the original.

let data = { 
  '2021-09-06': { Open: 24, },
  '2021-09-07': { Open: 80, Closed: 14, },
};

const result = Object.entries(data).map(([date, value]) => ({ date, Closed: 0, ...value }));

console.log(result);

  • Related