-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?

Andy
  • 61,948
  • 13
  • 68
  • 95
rudeTool
  • 526
  • 1
  • 11
  • 25
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"**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."_ – Andreas Sep 02 '21 at 16:47

2 Answers2

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);
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – Kevin M. Mansour Sep 03 '21 at 19:13
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);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • How about searching for a dupe instead of adding yet another duplicate answer (which happens to be the same as the [accepted answer](https://stackoverflow.com/a/49629733/402037) on the dupe target)? – Andreas Sep 02 '21 at 16:46