在JavaScript中将键添加到数组

时间:2018-11-19 15:29:39

标签: javascript arrays multidimensional-array

我有一个数据数组,第一行是标题:

[["Date", "Key1", "Key2", "Key3", "Key4"],
["2018-11-01", "254", "-", "-", "-"],
["2018-11-02", "648", "-", "-", "-"],
["2018-11-03", "270", "170", "-", "147"],
["2018-11-04", "300", "406", "136", "208"]]

我希望能够与D3库图一起使用的输出为:

[[Date: "2018-11-01", Key1: "254", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-02", Key1: "648", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-03", Key1: "270", Key2: "170", Key3: "-", Key4: "147"],
[Date: "2018-11-04", Key1: "300", Key2: "406", Key3: "136", Key4: "208"]]

我尝试了许多不成功的变体,使用javascript,并使用map来做到这一点。但是我无法做到这一点...按键是动态的,所以我不能使用固定键。 有人能帮我吗? 谢谢! 马努埃

3 个答案:

答案 0 :(得分:2)

对于对象数组,您可以映射值并获取分配给单个对象的映射对象。

var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
    result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您需要将内部数组映射到对象。您不能在数组构造内分配键值对。

var matrix = [
  [ "Date", "Key1", "Key2", "Key3", "Key4" ],
  [ "2018-11-01", "254", "-", "-", "-" ],
  [ "2018-11-02", "648", "-", "-", "-" ],
  [ "2018-11-03", "270", "170", "-", "147" ],
  [ "2018-11-04", "300", "406", "136", "208" ]
];

console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

function matrixToJsonObjectArray(matrix, includesHeader) {
 var fields = includesHeader ? matrix[0] : range(matrix[0].length);
 return (includesHeader ? matrix.slice(1) : matrix).map(row => {
  var obj = {};
  fields.forEach((field, i) => obj[field] = row[i]);
  return obj;
 });
}

function range(start, end) {
  var arr = [];
  if (end === undefined) end = start, start = 0;
  for (var i = start; i < end; i++) arr.push(i); 
  return arr;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 2 :(得分:0)

您可以创建一个zipObject方法,该方法使用Array.reduce()转换为对象数组,并将其与Array.map()结合使用,以将标头数组与其他数组组合在一起:

const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

// zip two arrays to an object
const zipObject = (keys) => (values) =>
  keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});
  
// convert a two dimensional array to object
const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

const result = arrToObj(data);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }