[英]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.