-1

I have a get response in the below format:

{
  "1":"a",
  "2":"b"
}

Now I want to convert this into array of objects like this:

[
{
  text:"1",value:"a"
},
 {
text:"2",value:"b"
}
]

I did it like this:

Array.from(response.data,([text,value])=>({text,value})

but its not working.

How can I do this?

1
  • How do I ask a good question?: "Describe the problem. "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it." Commented Sep 2, 2021 at 16:47

2 Answers 2

2

map over the Object.entries and return a new array of objects.

const obj = {
  "1":"a",
  "2":"b"
}

const out = Object.entries(obj).map(([text, value]) => {
  return { text, value };
});

console.log(out);

Sign up to request clarification or add additional context in comments.

1 Comment

How about searching for a dupe instead of adding yet another duplicate answer (which happens to be the same as the accepted answer on the dupe target)?
2

const data = {
  "1":"a",
  "2":"b"
};
const array = [];

for (const [key, value] of Object.entries(data)) {
  array.push({text: key, value});
}

console.log(array);

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.