0

I have this object

{TDD_rating: 80, Fluency_rating: 70, Debug_rating: 64, Model_rating: 53, Refactor_rating: 68,}

which I want in the format of this array

[
  { subject: 'TDD', score: 80 },
  { subject:  'Fluency', score: 70},
  { subject:  'Debug', score: 65},
  { subject:  'Model', score: 53},
  { subject:  'Refactor', score: 68},

];

I have tried to use Object.entries and map but can't seem to get there

2 Answers 2

1

You could use combination of Object.entries() and Array.prototype.map() method to get your result. Get the key value pairs using Object.entries() method and then map it to make your required object array.

const data = {
  TDD_rating: 80,
  Fluency_rating: 70,
  Debug_rating: 64,
  Model_rating: 53,
  Refactor_rating: 68,
};

const ret = Object.entries(data).map(([x, y]) => ({
  subject: x.replace('_rating', ''),
  score: y,
}));
console.log(ret);

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

4 Comments

awesome works perfectly! spent ages wondering how to do it
Hi sorry to ask again, but I realised I my output I needed is slightly different, I need it without the '_rating' in the subject? How can I do so?
@JohnnyYip, check it, I have updated the code. Please let me know is it okay now.
thanks again! Totally new to JS still so finding trouble with these simple things
1

You can use Object.keys and map method to achieve that,

const obj = {
  TDD_rating: 80,
  Fluency_rating: 70,
  Debug_rating: 65,
  Model_rating: 53,
  Refactor_rating: 68,
};

const result = Object.keys(obj).map((key) => ({ subject: key, score: obj[key] }));
console.log(result);

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.