[英]Remove Property dynamically from JSON Object
我必须从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;
}
}};
function deepObjectRemove(object, path) { const parts = path.split("."); let current; while (current = parts.shift()) { if (!object) { return; } const item = object[current]; if (item !== undefined) { if (!parts.length) { delete object[current]; } if (item instanceof Array) { return item.forEach((item) => deepObjectRemove(item, parts.join("."))); } } object = item; } } const object = { a: { b: { c: "1", d: 0 } }, b: [ { a: { b: "0", c: "1" } }, { a: { b: "0", c: "1" } } ] }; console.log("before", object); [ "abc", "bac" ].forEach((path) => deepObjectRemove(object, path)); console.log("after", object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.