I am trying to remove a property from the object by key.
It's very important to notice that I have the key in my variable, and i am unable to do the following:
delete obj.test.a
This is my code (which doesn't work)
var obj = {
b: 2,
test: {
a: 1
}
}
var abc = 'test.a';
delete obj[abc];
console.log(obj);
How can I acheive deleting obj.test.a without hardcoding, and instead taking the key from variable.
You can first split you string to array and then use reduce()
to match object you want to delete and delete it.
var obj = {"b":2,"test":{"a":1}} var abc = 'test.a'.split('.') abc.reduce(function(r, e, i) { if(i == abc.length - 1) delete r[e] return r[e] }, obj) console.log(obj);
Here is maybe more elegant approach
var obj = {"b":2,"test":{"a":1}} 'test.a'.split('.').reduce(function(r, e, i, arr) { return arr[i + 1] ? r[e] : (delete r[e]) }, obj) console.log(obj);
Example explaining my comment:
var obj = {
test: {
a: 'hello'
}
};
function deleteProp(obj, path) {
var props = path.split('.');
var currentObj = obj;
for(var i = 0; i < props.length; i++) {
var prop = props[i];
if(i == props.length - 1) {
delete currentObj[prop];
} else {
currentObj = currentObj[prop];
}
}
}
deleteProp(obj, 'test.a');
console.log(obj); // { test: {} }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.