I wrote a function to delete a property of a nested object dynamically, based on the given "path" to the property and the "key" it self.
Apparently my code is not dynamic enough because i using the if
which is not dynamic enough. And it only support the defined dept of object (by the number of if
i would need your professional advise to correct my code:
Below is the code:
var deleteProp = function (path, prop) {
console.log(path)
let keys = path.split('.');
console.log(keys)
if(keys.length == 1){
delete object[keys[0]]
}
if(keys.length == 2){
delete object[keys[0]][keys[1]]
}
if(keys.length == 3){
delete object[keys[0]][keys[1]][keys[2]]
}
if(keys.length == 4){
delete object[keys[0]][keys[1]][keys[2]][keys[3]]
}
}
A little side info, i did refer to this post but the let parent = keys.reduce((obj, key) => obj[key], jsonObj);
doesn't work as expected. The value of parent
some how become one of the key's value instead of construct the "path" for me(which i have no idea why). This is how i implement the code from that post:
var deleteProp = function (path, prop) {
console.log(path)
let keys = path.split('.');
console.log(keys)
let parent = keys.reduce((obj, key) => obj[key], jsonObj) //jsonObj is the nested JSON.
console.log(parent) // show the value of the key only
delete parent[prop]
}
For those who dono what is nested object, please refer to this sample:
const object1 = {
a: 1,
b: 2,
c: 3,
d: {
x: 1,
y: 2,
z: {
aa: 1,
bb: 2,
cc: 3
}
},
e:4,
f:{
dd:1,
ee:2,
ff:3,
gg:{
xx:1,
yy:2,
zz:3
}
},
g:[
{a:1},
{b:2},
{c:3}
]
};
For those who curious why i want to do so:
Because i have a function that will return me a path like "a.f.gg"
as a string when i lookup for "yy"
. After i got the path and the property then now i want to delete it.
Thank you in advance.