-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 ???
});
2
  • 1
    You cannot do that via mapping. You need to iterate through each object and combine them into a single object. Commented Aug 13, 2019 at 11:53
  • Just use Object.assign({}, ...my_array) Commented Aug 13, 2019 at 12:05

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.