0

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}]

3 Answers 3

2

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);

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

Comments

1

You could do this pretty simply if you use Object.entries and Array.prototype.reduce, like this:

const obj = {
  2: "1",
  3: "8",
  4: "12"
};

const arr = Object.entries(obj).reduce((accum, el) => {
  const [key, value] = el;

  accum.push({
    question_id: key,
    option_id: value
  });

  return accum;
}, []);

console.dir(arr);

Comments

1

Try using Object.entries and map combination.

const optionObject = { 2: "1", 3: "8", 4: "12" }

const result = Object.entries(optionObject).map(option => ({question_id: option[0], option_id: option[1]})) // If You want string to be number, use parseInt(option[0]) & parseInt(option[1])

console.log(result)

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.