Chipe Chipe - 4 days ago 8
Javascript Question

JavaScript: Deconstructing an object with arrays, to an array that has objects

I am having a hard time wrapping my head around how to do this. I have this object:

var objData = {
_Input_396__REPEAT15_374:["Bedroom2", "Bedroom3", "Bedroom4"],
_Input_396__REPEAT15_375:["1st", "2nd", "3rd"],
_Input_396__REPEAT15_376:["122", "133", "144"],
_Input_396__REPEAT15_377:["122", "133", "144"],
_Input_396__REPEAT15_378:["Bamboo", "FloorNone", "Cork"]
};


the length of each array will be the same as the others in the object, however the length will change, so a length of
3
wont always be the length.

I need to deconstruct into this:

var arrData = [
{
_Input_396__REPEAT15_374:"Bedroom2",
_Input_396__REPEAT15_375:"1st",
_Input_396__REPEAT15_376:"122",
_Input_396__REPEAT15_377:"122",
_Input_396__REPEAT15_378:"Bamboo"
},
{
_Input_396__REPEAT15_374:"Bedroom3",
_Input_396__REPEAT15_375:"2nd",
_Input_396__REPEAT15_376:"133",
_Input_396__REPEAT15_377:"133",
_Input_396__REPEAT15_378:"FloorNone"
},
{
_Input_396__REPEAT15_374:"Bedroom4",
_Input_396__REPEAT15_375:"3rd",
_Input_396__REPEAT15_376:"144",
_Input_396__REPEAT15_377:"144",
_Input_396__REPEAT15_378:"Cork"
}
];


What is the best way to achieve this?

Answer

You could iterate the keys of the object and then the arrays and build a new array with the all items.

Methods used

  • Object.keys for own properties of the object

  • Array#forEach for iterating a given array

  • Pattern x = x || defaultValue, test x for a truthy value and if not, then assign defaultValue to x.

var objData = { _Input_396__REPEAT15_374: ["Bedroom2", "Bedroom3", "Bedroom4"], _Input_396__REPEAT15_375: ["1st", "2nd", "3rd"], _Input_396__REPEAT15_376: ["122", "133", "144"], _Input_396__REPEAT15_377: ["122", "133", "144"], _Input_396__REPEAT15_378: ["Bamboo", "FloorNone", "Cork"] },
    arrData = [];

Object.keys(objData).forEach(function (k) {
    objData[k].forEach(function (a, i) {
        arrData[i] = arrData[i] || {};
        arrData[i][k] = a;
    });
});

console.log(arrData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments