1

Here is My input Object.

let data = {
  "01-02-20":[{id:1}],
  "23-02-20":[{id:1}]
}

I am trying convert array of objects by this code

let res = Object.entries(data).map(( [k, v] ) => ({ [k]: v }));

But I didn't get my expected value :

My expected result should be like this:

let result = [
  {
    date: '01-02-20',
    item: [{ id: 1 }],
  },
  {
    date: '23-02-20',
    item: [{ id: 1 }],
  },
]

How can I get my expected result?

  • Why do you want `item` to be an array? Is there a way you can have more than one value in that array? Or is this just a simplified example. – trincot Jun 24 '20 at 17:49

1 Answers1

1

You are using the date as key and the value as value in the resulting objects. Instead you should be using two key-value pairs, one for date using the key as value and one for item using the value as value, like so:

let res = Object.entries(data).map(( [k, v] ) => ({ date: k, item : v }));

More concise using shorthand property names:

let res = Object.entries(data).map(( [date, item] ) => ({ date, item }));

Demo:

let data = {
  "01-02-20": [{ id:1 }],
  "23-02-20": [{ id:1 }]
};

let res = Object.entries(data).map(( [date, item] ) => ({ date, item }));

console.log(res);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73