javascript - 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])));
解决方案
像这样的东西...
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)
推荐阅读
- docker - 从 Jenkins Docker 容器旋转 Docker / ECS 容器
- javascript - 在表单“action”之前输入“submit”做onclick
- rest - 用于查询参数的 aws apigateway swagger 文件的集成 uri 是什么?
- matlab - 如何在Matlab中将函数与多维常数矩阵集成?
- node.js - 在 Windows10 上重新安装 NodeJS 和 NPM 时出现问题
- angular - 如何通过选择角度选项来显示输入字段?
- stored-procedures - 在运行时创建执行 SQL 任务
- android - 我已将 JSON 数据加载到对象中,我无法将它们连接到数组适配器以在多个微调器上显示它们
- java - 使用 netbeans 命令行在 Windows 上编译 Autopsy
- python - 从两个字符串返回具有相同长度的交替字母