Chipe Chipe - 1 year ago 114
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
wont always be the length.

I need to deconstruct into this:

var arrData = [

What is the best way to achieve this?

Answer Source

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;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download