Fred
Fred

Reputation: 212

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

Upvotes: 0

Views: 46

Answers (3)

GirkovArpa
GirkovArpa

Reputation: 4922

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

Upvotes: 2

Naren
Naren

Reputation: 4480

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)

Upvotes: 1

Tom O.
Tom O.

Reputation: 5941

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

Upvotes: 1

Related Questions