Below the Radar Below the Radar - 7 months ago 22
Javascript Question

Javascript - map object members to return new flattened object

Is there a simpler way to achieve the code below? Answer using lodash will be also accepted.

var obj = {
dataTable: {
column1: ["1"],
column2: ["2"],
column3: ["3"]
},
dataTable2: {
column4: ["4"],
column5: ["5"],
column6: ["6"]
}
}

var result = {};
var keys = Object.keys(obj);

keys.forEach(function(key) {
var fields = Object.keys(obj[key]);
fields.forEach(function(field) {
result[field] = obj[key][field][0];
});
});

console.log(result)
---> {column1: "1", column2: "2", column3: "3", column4: "4", column5: "5", column6: "6"}

Answer

You can use forOwn function (https://lodash.com/docs#forOwn)

 var result = {};
    _.forOwn(object, function(value, key){
      result[key] = value[0];
    })

for 2-level nesting you could use that method twice:

var result = {};
_.forOwn(obj, function(value1, key){
  _.forOwn(value1, function(value2, key){
    result[key] = value2[0];
  })
})
Comments