我有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;
}
}