-3

What should I to turn this:

{
  "1": {"name": "John", "age": "20"},
  "2": {"name": "Sam", "age": "30"},
  "3": {"name": "Tim", "age": "40"},
  }

Into this:

[
  {"id": "1", "name": "John", "age": "20"},
  {"id": "2", "name": "Sam", "age": "30"},
  {"id": "3", "name": "Tim", "age": "40"},
]

Thank you :)

1
  • 2
    What have you tried? Did it go wrong? Did you get error messages? Please update the question with some code that shows an error or issue. Commented Apr 21, 2021 at 23:28

2 Answers 2

1

You can easily achieve this using Object.entries, map, and array destructuring

const obj = {
  "1": { name: "John", age: "20" },
  "2": { name: "Sam", age: "30" },
  "3": { name: "Tim", age: "40" },
};

const result = Object.entries(obj).map(([key, value]) => {
  return { id: key, ...value };
});

console.log(result);

using Object.keys

const obj = {
  "1": { name: "John", age: "20" },
  "2": { name: "Sam", age: "30" },
  "3": { name: "Tim", age: "40" },
};

const result = Object.keys(obj).map((key) => {
  return { id: key, ...obj[key] };
});

console.log(result);

using for..in loop

const obj = {
  "1": { name: "John", age: "20" },
  "2": { name: "Sam", age: "30" },
  "3": { name: "Tim", age: "40" },
};

const result = [];
for (let key in obj) {
  result.push({ id: key, ...obj[key] });
}

console.log(result);

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

Comments

0
function objectToArray(obj) {
    return Object.entries(obj).map(([id, value]) => ({
        id,
        ...value
    }))
}

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.