1

I have the following data structure:

const data = {
    school1:{location:'medway',score:6},
    school2:{location:'milan',score:8},
    school3:{location:'brooklyn',score:103,
    }

How can I convert it to the following format in javascript:

const data = [
    {name:'school1', location:'medway',score:6},
    {name:'school2', location:'milan',score:8},
    {name:'school3', location:'brooklyn',score:103}
    ]
6
  • 1
    Object.entries(data).map(([k,v]) => ({name:k,...v})) Commented May 11, 2023 at 17:19
  • every answer looks the same as the comment,,,, Commented May 11, 2023 at 17:25
  • @ChrisG i was too lazy atm to write an answer Commented May 11, 2023 at 17:27
  • @cmgchess more like other ppl too lazy to come up with a different method Commented May 11, 2023 at 17:28
  • @ChrisG i think this one is a common question that's why many came up with same answer Commented May 11, 2023 at 17:29

1 Answer 1

1

You can map over the entries of the object.

const data={school1:{location:"medway",score:6},school2:{location:"milan",score:8},school3:{location:"brooklyn",score:103}};
const res = Object.entries(data).map(([name, v]) => ({name, ...v}));
console.log(res);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.