Javascript Typescript迭代记录类型并返回更新的记录
我不熟悉Typescript,我需要迭代Javascript Typescript迭代记录类型并返回更新的记录,javascript,typescript,ecmascript-6,typescript2.0,Javascript,Typescript,Ecmascript 6,Typescript2.0,我不熟悉Typescript,我需要迭代记录类型,对值进行一些更新,并返回记录 以下是类型的定义方式: type Parent = Readonly<Record<string, Children>>; type Children = ReadonlyArray<string>; 更新记录中的值的方法: const updateChildren = (child: Children) : Children => { return child.m
记录
类型,对值进行一些更新,并返回记录
以下是类型的定义方式:
type Parent = Readonly<Record<string, Children>>;
type Children = ReadonlyArray<string>;
更新记录中的值的方法:
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代码片段,并在下面的示例中获取updatemap
const数据={
父1:[“child1”、“child2”],
父母2:[“子女1”、“子女2”]
};
函数更新儿童(儿童){
返回children.map(child=>child+'updated');
}
const updatemap=新映射();
for(对象项(数据)的常量[键,值]){
updatemap.set(key,updateChildren(value));
}
updatemap.forEach((值,键)=>console.log(键+”:“+value));
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)
type Children=ReadonlyArray;
常量数据:父项={
父1:[“child1”、“child2”],
父2:[“child1”、“child2”],
};
类型MutableObject={-readonly[P in keyof T]:T[P]};
const updateChildren=(子项:子项):子项=>{
返回child.map(value=>value+'updated');
}
让newObj:Parent=Object.entries(data.reduce)(acc,cur)=>{
acc[cur[0]]=updateChildren(cur[1]);
返回acc;
}, {})
console.log(newObj)
我正试图写类似的东西,但是对于父类
类型,而不是这个代码段中的map对象.keys(data).reduce((map,currentItem)=>{const updated=updateChildren(data[currentItem]);return map.set(currentItem,updated)},new map()代码>因此,如果我可以传递{}
而不是尝试为其提供语法;我已经接受了答案,您可以更新它以反映repl中的更改
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)