Javascript - 如何将对象数组映射到具有列名的数据表?

Javascript - How do I map an array of objects to a datatable with column names?

我有一些这样的数据,一个对象数组:

source = [{
  day: 1,
  deliveries: 16,
  hours: 9
}, {
  day: 2,
  deliveries: 19,
  hours: 11
}]

我想要这种格式:

source = (['day', 'deliveries', 'hours'],
          ['1', '16', '9'],
          ['2', '19', '11'])

有点像 table。我阅读了一些关于映射数组的内容并尝试了这个:

const datatable = source.map(d => Array.from(Object.keys(d)))
console.log(datatable)
// [["day", "deliveries", "hours"], ["day", "deliveries", "hours"]]

还有这个:

const datatable = source.map(d => Array.from(Object.values(d)))
console.log(datatable)
// [[1, 16, 9], [2, 19, 11]]

每个人都给了我想要的一半。 我试过这个:

let datatable = source.map(d => Array.from(Object.keys(d)))
let datatable2 = source.map(d => Array.from(Object.values(d)))

datatable = datatable[1]
let combined = datatable.concat(datatable2);
console.log(combined)
///["day", "deliveries", "hours", [1, 16, 9], [2, 19, 11]]

但即使在这里,列名也没有正确组合,这种方式似乎有点混乱。我如何让键位于顶部(就像列名一样)以及它们后面的值?

假设您希望 source 是一个数组数组(常见于 table 类结构),获取键一次,然后添加将对象属性映射到键的每一行数组该指数:

const keys = Object.keys(source[0]);
const result = [keys, ...source.map(obj => keys.map(key => obj[key]))];

实例:

const source = [{
  day: 1,
  deliveries: 16,
  hours: 9
}, {
  day: 2,
  deliveries: 19,
  hours: 11
}];

const keys = Object.keys(source[0]);
const result = [keys, ...source.map(obj => keys.map(key => obj[key]))];
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}

请注意,这假设了一些事情:

  1. source数组总是至少有一个对象。
  2. source 数组中的对象都具有相同的属性集。
  3. 您希望键按照它们在数组中第一个对象中出现的顺序排列。 (JavaScript 对象属性 do 现在有定义的顺序,但使用该顺序几乎不是一个好主意,所以你可能想做一些 sort keys 上的操作。)

你快到了。只需使用 [0] 获取第一项即可仅获取密钥。然后使用 ....

组合数组

let source = [{
  day: 1,
  deliveries: 16,
  hours: 9
}, {
  day: 2,
  deliveries: 19,
  hours: 11
}]

let ansArray = Object.keys(source[0]);
let datatable = source.map(d => Array.from(Object.values(d)))

let combined = [ansArray,...datatable];
console.log(combined);

如果属性顺序错误,

Array.from(Object.keys(d))Array.from(Object.values(d))将return错误数据。

const source = [{
  day: 1,
  deliveries: 16,
  hours: 9
}, {
  day: 2,
  deliveries: 19,
  hours: 11
}]

const datatable = source.reduce((acc, item, index) => {
   if (index == 0) {
     acc.push(Object.keys(item));
   }
   const newRow = acc[0].reduce((rowAcc, prop) => {
     rowAcc.push(item[prop]);
     return rowAcc;
   }, []);
   
   acc.push(newRow);
  return acc;
}, [])

console.log(datatable);