Javascript - 将对象成员映射到 return 新的展平对象

Javascript - map object members to return new flattened object

是否有更简单的方法来实现下面的代码?使用 lodash 的回答也将被接受。

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"}

可以使用forOwn函数(https://lodash.com/docs#forOwn)

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

对于 2 级嵌套,您可以使用该方法两次:

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

你可以使用递归:

myFn= (u,o,k)=> {
    if (o.map == [].map) u[k] = o[0];
    else for (k in o) myFn(o[k],k)
}

以上函数将搜索 ALL 个嵌套级别,并相应地填充您的对象。

要使用,简单的这样做:

var output = {};
myFn(output, obj);

console.log(output);
// {column1: "1", column2: "2", column3: "3", column4: "4", column5: "5", column6: "6"}

你可以用两个 for...in 循环来做到这一点

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

for (p in obj) {
  for (a in obj[p]) {
    result[a] = obj[p][a].join('');
  }
}

console.log(result);

ES6 真正发挥作用的任务。

const res = Object.assign(...Object.keys(obj).map(x => obj[x]))
Object.keys(res).forEach(x => res[x] = res[x][0])

这是一个使用 reduce() to merge() all datatable objects and then use mapValues() to set each of the column values by using head().

的 lodash 解决方案

DEMO

var result = _.chain(obj)
  .reduce(_.merge) // merge all values
  .mapValues(_.head) // set the first item of the array as the value
  .value();