gpt4 book ai didi

javascript - Typescript 遍历 Record 类型并返回更新的 Record

转载 作者:行者123 更新时间:2023-12-04 12:58:19 78 4
gpt4 key购买 nike

我是 的新手 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]))
我想我很接近但不确定如何返回 map ,因为这里返回 Array [Array]是否有一些很好的方法来迭代更新,它会以使用的相同类型返回更新的数据。
谢谢阅读。
这是我正在尝试执行并获取 updatedMap 的 javascript 片段在下面的示例中。

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)

关于javascript - Typescript 遍历 Record 类型并返回更新的 Record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62905565/

78 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com