Here is the small utility function which I wrote it when I fell into the requirement stated below:Introduction
"Given a Javascript object having a lot of attributes, I am given a path for a particular attribute which is to be removed."
My Thought process
- Recursion come up in my mind by noticing that there can be variable length of the path for the particular attribute to be deleted.
- After searching for sometime I got to know that I cannot (or is very hard) make the deletion happen on the fly (I was thinking of pass by reference) and just return the result. So I came up with the idea of overwrite
- Someway or the other each recursion level on completion should be able to return 2 things whichever suits the case. Two things are -
- Whether the path was correct and any attribute was able to get deleted
- If deletion was successful return the updated object (or array) and traverse it to the parent level and update subsequent attribute (or array elements)
Here is the recursive function which fulfils the requirementCode Section
function getDeletedObj(obj, attr) {
if (typeof obj === 'undefined') {
// We came across improper attribute while traversing the list of attribute in `attr`
return false;
} else if (attr.length === 0) {
// when we have traversed the complete `attr` path correctly
return true;
} else {
var key = attr[0];
var isArray = false;
if (Object.prototype.toString.call(obj) === '[object Array]') {
isArray = true;
}
var objectFound = getDeletedObj(obj[key], attr.slice(1));
if (objectFound === false) {
// We went to the path of the object which did not existed (see the 'undefined' check above)
return false;
} else if (objectFound === true) {
// the next call was the last call to the attribute which is to be removed
if (isArray) {
// If the object to be removed was a part of array, then splice it
obj.splice(key, 1);
} else {
// Otherwise delete the object
delete obj[key];
}
} else {
// If neither `true` nor `false` is returned that means the returned variable is the updated object
// Update the current object and return it back for higher level updation
obj[key] = objectFound;
}
return obj;
}
}
Here's how you would use it: exampleObj = {
a: {
b: 1,
c: [1,2,3]
},
d: true
}
result = getDeletedObj(exampleObj, ['a', 'c', 1])
Output:Wordpress version
result = {
a: {
b: 1,
c: [1,3]
},
d: true
}
No comments:
Post a Comment