Transform an array into an array of objects

I have this object:

{2: "1", 3: "8", 4: "12"}

What is the best way to transform it into an array of objects like this:

I understand that I must iterate using the .map or a forEach, however, how will I get the index and the value and add in separate “keys”?

[{question_id:2, option_id: 1}, {question_id: 3, option_id: 8}, {question_id: 4, option_id: 12}]

Answer

This is probably the shortest code possible to achieve what you want:

Object.entries(obj).map(([k, v]) => ({ question_id: k, option_id: v }));

const obj = { 2: "1", 3: "8", 4: "12" };
const res = Object.entries(obj)
  .map(([k, v]) => ({ question_id: k, option_id: v }));
console.log(res);

Leave a Reply

Your email address will not be published. Required fields are marked *