这个问题在这里已有答案:
我有JSON对象...并且想要从每个孩子到最后一个孩子删除名称键值,即(name-11,name-22)...使用java脚本函数...
{
"id": "1",
"name": "11",
"child": [
{
"id": 2,
"name": "22",
"child": [
{
"id": 3,
"name": "33",
"child": [
{
"id": 4,
"name": "44",
"child": [
{
"id": 5,
"name": "55",
"child": [
{
"id": 6,
"name": "66"
}
]
}
]
}
]
}
]
}
]
}
有没有正确的方法呢?
可能是这样的......
let myJson = {
"id": "1",
"name": "11",
"child": [{
"id": 2,
"name": "22",
"child": [{
"id": 3,
"name": "33",
"child": [{
"id": 4,
"name": "44",
"child": [{
"id": 5,
"name": "55",
"child": [{
"id": 6,
"name": "66"
}]
}]
}]
}]
}]
};
let currentObject = myJson;
while (currentObject.child && currentObject.child[0]) {
delete currentObject.name;
currentObject = currentObject.child[0];
}
console.log(myJson)
javascript有一个删除操作符,它的工作方式如下:
delete object.name
现在你可以将它与for循环一起使用并删除每个条目