Typescript 4.1.5排列操作员问题
我创建自己的接口Typescript 4.1.5排列操作员问题,typescript,Typescript,我创建自己的接口 interface MyType { [key :string] :boolean } 我想使用扩展操作符用新对象更新数组元素。比如说: aList = new Array<MyType >({['something']:true,['something2']:true}); 但我仍然得到了错误,或者B像新元素一样添加到列表中。有什么不对劲吗 我不能只过滤列表,因为在我的场景中,B是任何类型的$event @Wiktor, 晚上好下面是代码 inter
interface MyType {
[key :string] :boolean
}
我想使用扩展操作符用新对象更新数组元素。比如说:
aList = new Array<MyType >({['something']:true,['something2']:true});
但我仍然得到了错误,或者B像新元素一样添加到列表中。有什么不对劲吗
- 我不能只过滤列表,因为在我的场景中,B是任何类型的$event
- @Wiktor,
晚上好下面是代码
interface MyType {
[key: string]: boolean
}
let aList = new Array<MyType>({ ['something']: true }, { ['something2']: true });
console.log(aList);
const B: MyType = { ['something']: false };
for (let index = 0; index < aList.length; index++) {
console.log(`${JSON.stringify(aList[index])} === ${JSON.stringify(B)}`);
for (let destinationProperty in aList[index]) {
for (let sourceProperty in B) {
if (destinationProperty === sourceProperty) {
aList[index] = B;
}
}
}
}
console.log(aList);
接口MyType{
[键:字符串]:布尔值
}
设aList=新数组({['something']:true},{['something2']:true});
控制台日志(aList);
常量B:MyType={['something']:false};
for(让index=0;index
您目前实际上并没有存储
MyType
的数组,而是将aList
初始化为包含数组的对象。定义如下所示:
let aList: MyType[] = [{'bbb':true}, {'aaa':true}];
现在,
列表是一个数组,而不是一个对象。使用列表。按下(b)。但是如果你坚持使用排列运算符,那么就用
[…aList,B]
而不是{…aList,B}
@NicholasK实际上我不能,我必须用相同的key@SimonCheng我已经试过了,但它返回的数组只包含新元素——这里的示例@nicholk问我,在我的场景中,B对象实际上是一个带有“any”类型的$event,你知道怎么做吗?(这是一个处理来自另一个组件的@output()的方法)您想用aList
做什么?您是否正在尝试执行aList:MyType[]=[{'something':true},{'something2':true}]
?此解决方案基本上是将数组中的两个对象替换为B。我要找的是替换列表中唯一一个键与B键匹配的值。我正在努力。请给我几分钟更新代码。工作正常,相当复杂的解决方案,但它是有效的,你知道为什么只是基本的{…这个.aList,B}不起作用吗?
let aList: MyType[] = [{'bbb':true}, {'aaa':true}];
// find out the key that needs to be replaced
let keyToFind = '';
for (let obj in B) {
keyToFind = obj;
}
// loop over aList to see if there is a match for `keyTofind`;
// if found then replace that index and break
aList.forEach((obj, index) => {
for (let key in obj) {
if (key === keyToFind) {
aList[index] = B;
break;
}
}
})