Sudhir Mishra Sudhir Mishra - 16 days ago 5
Javascript Question

Change the nested object structure from array of objects to a common object and remove old array of objects

I have an object structure like this:

{
"name":"Garden",
"live":true,
"isUpdated":true,
"categories":[
{
"min":0,
"max":0,
"required":true,
"category":"flower",
"options":[
{
"optionName":"Blue",
"optionValue":16.95
}, {
"optionName":"Red",
"optionValue":55.95
}
]
}
]
},


I want to change above structure to this one:

{
"name":"Garden",
"live":true,
"isUpdated":true,
"categories":[
{
"min":0,
"max":0,
"required":true,
"category":"flower",
"Blue":16.95,
"Red":55.95
}
]
}


Basically I want to change options object.

"Options":

[
{
"optionName":"Blue",
"optionValue":16.95
}, {
"optionName":"Red",
"optionValue":55.95
}
]


To this

"Blue":16.95,
"Red":55.95


Any JavaScript or lodash based solutions or suggestions are welcomed.

Answer

Using lodash. I hope this helps you.

var mObj = {
    "name":"Garden",
    "live":true,
    "isUpdated":true,
    "categories":[
       {
          "min":0,
          "max":0,
          "required":true,
          "category":"flower",
          "options":[
             {
                "optionName":"Blue",
                "optionValue":16.95
             },
             {
                "optionName":"Red",
                "optionValue":55.95
             }
          ]
       }
    ]
};
               
mObj.categories.forEach(function(category){
      var transformedOption = _.transform(category.options, function(result, obj) {
             return _.assign(result, { [obj.optionName] : obj.optionValue});
      }, {});
category = _.assign(category, transformedOption);
 _.unset(category, "options");
})

console.log(mObj);
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.js"></script>

Comments