Javascript映射对象成员以返回新的扁平对象

Javascript - map object members to return new flattened object

本文关键字:对象 映射 成员 Javascript 返回      更新时间:2023-09-26

有没有更简单的方法来实现下面的代码?使用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"}

您可以使用两个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);

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

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

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

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

ES6真正闪光的任务类型。

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

这里有一个lodash解决方案,它使用reduce()合并所有datatable对象,然后使用mapValues()通过使用head()设置每个column值。

演示

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

您可以使用递归:

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