首页 > 解决方案 > Typescript 遍历 Record 类型并返回更新的 Record

问题描述

我是Typescript的新手,我需要迭代一个Record类型,对值进行一些更新并返回Record.

这是定义类型的方式:

type Parent = Readonly<Record<string, Children>>;
type Children = ReadonlyArray<string>;

这是我想迭代的一些示例数据:

const data = {
    parent1: ["child1", "child2"],
    parent2: ["child1","child2"]
};

更新记录中的值的方法:

const updateChildren = (child: Children) : Children => {
    return child.map( value => value + 'updated');
}

我正在努力为其编写语法,试图寻找示例但找不到任何有用的东西。

我可以使用迭代记录Object.entries

Object.entries(data).forEach(([key, value]) => console.log(key, value));

我也尝试使用Object.keys

Object.keys(data)
            .map(key => updateChildren(data[key]))

我想我很接近但不知道如何返回地图,因为它在这里返回Array [Array]

是否有一些很好的方法来迭代更新,它会以使用的相同类型返回更新的数据。

谢谢阅读。

这是我正在尝试做的事情的 javascript 片段,并获得updatedMap下面的示例。

const data = {
    parent1: ["child1", "child2"],
    parent2: ["child1","child2"]
};

function updateChildren(children) {
  return children.map(child => child+'updated');
}

const updatedMap = new Map();

for (const [key, value] of Object.entries(data)) {
  updatedMap.set(key, updateChildren(value));
}

updatedMap.forEach((value, key) => console.log(key + ":" + value));


console.log(Object.keys(data).map(key => updateChildren(data[key])));

标签: javascripttypescriptecmascript-6typescript2.0

解决方案


像这样的东西...

type Children = ReadonlyArray<string>;

const data: Parent = {
  parent1: ["child1", "child2"],
  parent2: ["child1", "child2"],
};


type MutableObject<T> = { -readonly [P in keyof T]: T[P] };

const updateChildren = (child: Children): Children => {
  return child.map(value => value + 'updated');
}

let newObj: Parent = Object.entries(data).reduce<MutableObject<Parent>>((acc, cur) => {
  acc[cur[0]] = updateChildren(cur[1]);
  return acc;
}, {})

console.log(newObj)


推荐阅读