JavaScript:使用第一个“行”将二维数组转换为对象数组来定义属性

javascript: convert two dimensional array to array of objects using the first 'row' to define properties

本文关键字:对象 转换 数组 属性 定义 二维数组 第一个 JavaScript      更新时间:2023-09-26

为了填充接收行对象数组的数据网格,我正在寻找一个很好的解决方案来转换这样的数组:

[  
['country', 'population'],
['someplace', 100],
['otherplace', 200]
]

放入一个对象数组中,例如:

[
{country: 'someplace', population: 100},
{country: 'otherplace', population: 200},
]

更新:

这是我到目前为止使用的解决方案:

 function arrayToRows(arr) {
var defs = [];
var data = [];
var rows = [];
var r;
var obj;

var headerRow = arr.shift(); //remove header row
defs = headerRow.map(function(cell) {
  return {
    field: cell,
    displayName: cell
  }
});

for (var i = 0; i < arr.length; i++) {
  r = arr[i];
  obj = {};
  for (var j = 0; j < defs.length; j++) {
    obj[defs[j].field] = r[j];
  }
  rows.push(obj);
}
return rows;

}

var array = [  
    ['country', 'population'],
    ['someplace', 100],
    ['otherplace', 200]
];
var keys = array.shift();
var objects = array.map(function(values) {
    return keys.reduce(function(o, k, i) {
        o[k] = values[i];
        return o;
    }, {});
});

let array = [['country', 'population'],['someplace', 100],['otherplace', 200]];
let [keys, ...rows] = array;
let result = rows.map(r => (keys.reduce((o, k, i) => (o[k] = r[i], o), {})));
console.log(result)

嘿,通过使用库下划线.js (http://underscorejs.org/#object) 您可以像这样轻松地完成此操作:

var array = [['country', 'population'],['someplace', 100],['otherplace', 200]];
var output = [];
for(var index=1; index<array.length; index++){
    output.push(_.object(array[0],array[index]));
}
console.log(output);

检查此链接:http://jsfiddle.net/BqA3Y/2/

使用 map 和 forEach 的组合,您可以将后续数组元素映射到第一个元素中指定的列。

var arr = [  
   ['country', 'population'],
   ['someplace', 100],
   ['otherplace', 200]
];
var cols = arr.shift();
newArr = arr.map(function(element,index){
   var newObj = {};
   element.forEach(function(data,index){
      newObj[cols[index]]=data;
   });
   return newObj;
});
var array = [
    ['country', 'population'],
    ['someplace', 100],
    ['otherplace', 200]
];
var objects = [], one = array[0][0], two = array[0][1];
for (var i = 1, len = array.length; i < len; i++) {
    var object = {};
    object[one] = array[i][0];
    object[two] = array[i][1];
    objects.push(object);
}
console.log(objects);

演示

您需要使用一些迭代来执行此操作!以下代码是一个未经测试的示例,用于演示您必须执行的操作。

function convertToObjectArray(table)
{
    var output = [];
    for(var i = 1; i < table.length; i++)
    {
        var obj = {};
        for(var x = 0; x < table[0].length; x++)
         obj[table[0][x]] = table[i][x];
         output.push(obj);
    }
    return output;
}

此示例的另一个注意事项是,您应该对其进行编辑,以确保后续数组的长度相同,否则可能会遇到 null 值。

你可以

很好地用解构和Object.fromEntries()做到这一点:

const arr = [ ['country', 'population'], ['someplace', 100], ['otherplace', 200] ];
const [props, ...valsArr] = arr;
const res = valsArr.map(vals => Object.fromEntries(vals.map((val, i) => [props[i], val])));
console.log(res);

解释:

const [props, ...valsArr] = arr

这将创建两个新变量,props数组中的第一个值:

['country', 'population']

valsArr是数组中的剩余元素:

[ ['someplace', 100], ['otherplace', 200] ]

接下来,我们在此数组上使用.map()将每个内部[place, population]数组映射到对象数组。为此,我们在每个[place, population]数组的映射版本上使用Object.fromEntries()。每个内部数组的映射版本将变为:

[
  ["country", place],  // props[i] would be 'country' from the above `props` array
  ["population", population] // props[i+1] would be 'population' from the above `props` array
]

上面的[prop, value]内部数组数组可以传递给 Object.fromEntries() ,这将是您的对象,其中包含第一个索引中的键和第二个索引的值。

function toObjects (array) {
  var new_array = [];
  var headers = [];
  for(var i = 0; i < array.length; i++){
    var obj = {};
    for(var j = 0; j < array[i].length; j++){
      if(i === 0){
        headers.push(array[i][j]);
      } else {
        obj[headers[j]] = array[i][j];
      }
    }
    if(i > 0){
      new_array.push(obj);
    }
  }
  return new_array;
}