-1

Here is my response from my server.

var my_array = [{"1":"1"},{"2":"8"},{"4":"13"},{"5":"19"},{"6":"22"}]; //from server

I want to convert it like

var new_array = { 1 : "1", 2 : "8", 4 : "13", 5 : "19" , 6 : "22"}

But how to convert it using map function

new_array = my_array.map(function (a) {
    return ???
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Ashis Biswas
  • 747
  • 11
  • 28

1 Answers1

2

Use reduce with spreading - you can't map an array to an object. Spreading also allows for multiple properties in each object.

var new_array = my_array.reduce((a, c) => ({ ...a, ...c }), {});

You could also use Object.fromEntries after flatMapping the entries:

var new_array = Object.fromEntries(my_array.flatMap(Object.entries));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79