typescript 将列结构数组转换为行

myzjeezk  于 2023-01-14  发布在  TypeScript
关注(0)|答案(2)|浏览(151)

我很抱歉问你,但是每次我需要做这样的事情时,我都会感到很困惑,每次我陷入多个循环,我做出的最终决定看起来很可怕。
假设你有这样一个对象:

export interface Data {
    id: number;
    type: string;
}

和该对象的数组:

let data: Data[] = [
     { id: 1, type: 'one' },
     { id: 2, type: 'two' }
];

创建这样的数组最简单/安全的方法是什么:

arrdata = [
   [1, 2],
   ['one', 'two']
];

其原理类似于将列结构数据转换为行:

1,2
1,2
1,2

1,1,1
2,2,2
baubqpgj

baubqpgj1#

创建空数组的数组,其数目等于键计数。
然后对于data中的每个对象,我们遍历每个key并将其推入相应的数组。

const data = [
  { id: 1, type: "one" },
  { id: 2, type: "two" },
  { id: 3, type: "three" }
];

const keys = Object.keys(data[0]).sort();
const arrData = new Array(keys.length).fill(0).map((_) => []);
data.forEach((d) => keys.forEach((k, i) => arrData[i].push(d[k])));

console.log(arrData);
toiithl6

toiithl62#

可以像这样使用array.prototype.reduce

let data = [
     { id: 1, type: 'one' },
     { id: 2, type: 'two' }
];

const initialData = [[],[]]

const newData = data.reduce((acc, { id, type }) => {
  acc[0].push(id);
  acc[1].push(type);
  return acc;
}, initialData)

console.log(newData)

相关问题