如何从数组中创建对象?

How to make object from array?

如何从数组创建对象

 { A: {H: 10,
       W: 20,
       S: 30}}

来自

 [
   { group: A, name: H, value: 10 },
   { group: A, name: W, value: 20},
   { group: A, name: S, value: 30}
 ]

在打字稿中

使用:

  • map 转换数组项
  • Object.entriesObject.fromEntries
const groupBy = <T>(array: T[], predicate: (v: T) => string) =>
  array.reduce((acc, value) => {
    (acc[predicate(value)] ||= []).push(value);
    return acc;
  }, {} as { [key: string]: T[] });

const a = [
   { group: 'A', name: 'H', value: 10},
   { group: 'A', name: 'W', value: 20},
   { group: 'A', name: 'S', value: 30}
 ];

const transformSingleItemToEntry = (it: {name: string, value: number}) => [it.name,  it.value];

const groupped = groupBy(a, it => it.group);
const newObject = Object.fromEntries(
  Object.entries(groupped).map(
    e => [e[0],  Object.fromEntries(e[1].map(transformSingleItemToEntry)) ]
  )
);
console.log(newObject);

Playground link

为了转换对象数组,并将它们的键提取到变量,我们可以使用 Array reducer。

要定义我们的类型,TypeScript Record 应该可以解决问题,这适用于具有可变键的对象。

我们遍历数组的条目,将对象变成 key-value 元组的数组,然后遍历该对象的值的条目,以便将它们提取到名称中,和价值。该组可以从外部元组的键中推断出来。

type InnerRecord = Record<string, number>;
type OuterRecord = Record<string, InnerRecord>;

interface TransformedRecord {
    group: string;
    name: string;
    value: number;
};

const record: OuterRecord = {
  A: { H: 10, W: 20, S: 30 },
  B: { H: 15, W: 25, S: 35 },
  C: { H: 20, W: 30, S: 40 },
};

const transformRecord = (toTransform: OuterRecord) => {
  return Object.entries(toTransform).reduce(
    (accumulator, [group, values]) => [
      ...accumulator,
      ...Object.entries(values).map(([name, value]) => ({ group, name, value, })),
    ],
    []
  );
};

const transformed: TransformedRecord[] = transformRecord(record);

console.log(transformed);
/** OUTPUT:
 *    [ { group: 'A', name: 'H', value: 10 },
        { group: 'A', name: 'W', value: 20 },
        { group: 'A', name: 'S', value: 30 },
        { group: 'B', name: 'H', value: 15 },
        { group: 'B', name: 'W', value: 25 },
        { group: 'B', name: 'S', value: 35 },
        { group: 'C', name: 'H', value: 20 },
        { group: 'C', name: 'W', value: 30 },
        { group: 'C', name: 'S', value: 40 } ]
 */

这将使我们从嵌套对象数组变为 one-dimensional 对象数组。