我必须从 JSON 对象中删除属性。就像我需要编写一个框架,在其中传递需要编辑字段的位置数组。我的 JSON 请求看起来像这样
{
"name": "Rohit",
"other": [{
"tfn": "2879872934"
}, {
"tfn": "3545345345"
}],
"other1": {
"tfn": "3545345345"
},
"other2": {
"other3": [{
"tf2n": "2879872934"
}, {
"tfn": "3545345345"
}, {
"tfn": "2342342234"
}]
},
"card": "sdlkjl",
"tfn": "2879872934",
"f": true}
正如我上面所说,这就是我捕获需要删除的位置的方式
let paths = ['other.tfn','tfn','other1.tfn','other2.other3.tfn'];
它从几乎所有地方删除 tfn 字段并返回
{
"name": "Rohit",
"other": [
{},
{}
],
"other1": {},
"other2": {
"other3": [
{
"tf2n": "2879872934"
},
{},
{}
]
},
"card": "sdlkjl",
"f": true}
我很好奇是否有人可以建议一种更好的方法来编写下面的代码
paths.forEach(function (path) {
let keys = path.split('.');
deepObjectRemove(jsonObject, keys);
});
方法
var deepObjectRemove = function(obj, path_to_key){
if(path_to_key.length === 1){
delete obj[path_to_key[0]];
return true;
}else{
if(obj[path_to_key[0]] && Array.isArray(obj[path_to_key[0]])) {
obj[path_to_key[0]].forEach(function (value) {
deepObjectRemove(value, path_to_key.slice(1));
});
//return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
}else if(obj[path_to_key[0]]){
deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
}else{
return false;
}
}};