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
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);
answered Mar 15, 2021 at 18:36
GirkovArpa
5,1015 gold badges19 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Mar 15, 2021 at 18:30
Tom O.
5,9813 gold badges24 silver badges36 bronze badges
Comments
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)
answered Mar 15, 2021 at 18:33
Naren
4,5293 gold badges20 silver badges32 bronze badges
Comments
lang-js