将对象设置为 null 以匹配 ES6/TS 中的通过突变设置中的匹配条件



我有Set嵌套如下的对象:

const mySet: Set<any> = new Set([
{
id: 1,
text: "hello",
success: true,
sub: {
id: 5,
text: 'hi',
success: true,
sub: {
id: 7,
text: 'hi ...',
success: true,
sub: {
id: 12,
text: 'hi :)',
success: false,
}
}
},
{
id: 2,
text: "hey",
success: true,
sub: null,
}
])

正如你所看到的id:1有一个sub,它也有自己的sub,它像这样继续下去。这可能介于 0 到 X 之间。我想做的是,找到成功false并将对象更改为null并保留数组。

我试过这个。这突变:

mySet.forEach(s => {
s.text = "Override text"
})
// OR... This works for first element but what about recursively?
mySet.forEach(s => {
if(s.sub.success === false) s.sub = null
})

这样我就可以覆盖值。forEach改变原始对象。但是我该如何为多个潜艇做到这一点呢?我对此一无所知。

基本上,如果sub存在,我想迭代并递归迭代,如果找到,则将其设置为null如果成功false

预期成果:

[
{
id: 1,
text: "hello",
success: true,
sub: {
id: 5,
text: 'hi',
success: true,
sub: {
id: 7,
text: 'hi ...',
success: true,
sub: null
}
},
{
id: 2,
text: "hey",
success: true,
sub: null,
}
]

有什么建议吗?

这就是我到目前为止尝试过的。我把它放在forEach但这替换了所有对象,而不是找到的最后一个元素。

do {
if (sub.success === false) {
m.sub = null
} else {
m.sub = m.sub.sub
}
}
while (m.sub !== null)

您可以创建将对象作为参数的函数。如果success为假,则设置为sub = null。否则,如果对象具有非 nullsub属性,则递归调用obj.sub对象上的函数。使用forEach为数组或集中的每个项目调用此函数

const input = new Set([{id:1,text:"hello",success:true,sub:{id:5,text:"hi",success:true,sub:{id:7,text:"hi ...",success:false,sub:{id:12,text:"hi :)",success:false,}}},},{id:2,text:"hey",success:true,sub:null,}]);
function checkSub(obj) {
if (!obj.success)
obj.sub = null
else if (obj.sub)
checkSub(obj.sub)
}
input.forEach(checkSub)
console.log([...input]) 
// Set won't be displayed in the snippet console
// so, converting it to an array for demo

m.sub = m.sub.sub中,你使用m.sub作为"迭代变量"。请改用局部变量。

var obj = …;
while (obj.sub) {
if (!obj.sub.success) {
obj.sub = null;
} else {
obj = obj.sub;
}
}

你也可以把它写成

for (var obj = …; obj.sub; obj = obj.sub) {
if (!obj.sub.success) {
obj.sub = null;
break;
}
}

最新更新