I am having one object similar to below,
let obj = {
"mode1":{
"pool_1":[
{ "id":115 },
],
"pool_2":[
{ "id":116 }
],
"pool_4":[
{ "id":117 }
],
},
"mode2":{
"pool_6":[
{ "id":122 }
]
},
"mode3":{
"pool_1":[
{ "id":123 }
]
},
"AWS":{
"cloud":[]
},
"Azure":{
"cloud":[]
}
}
let value_array = ["pool_1"];
Here,
Step 1 : I need to remove the property from the obj which matches the value_array. For example, in the above code, pool_1
should get removed from mode1' and
mode3`
Step 2 : Need to check all the keys of the obj
and push the empty keys into new array. For example, in the above code, mode3
should be added into a new array like ["mode3"]
Output should be like below,
["mode3"]
because, mode3
is having empty object.
This is working when using the for loops. But I need to use some simple way like Lodash or Es6 methods to achieve this. Any help would be much appreciated.
Tried like below,
for (var key in obj) {
for (var keys in obj[key]) {
value_array.forEach(function (item) {
if(keys == item){
console.log(key)
delete obj[key][keys]
}
console.log("ALL THE DETALS AFTER DELETE", obj)
});
}
}
We can create a function, deleteRecursive or something like that, traverse the object and deleted the required keys.
We'll also build up a list of empty keys.
function deleteRecursive(input, keysToDelete, inputKey = "", emptyKeys = []) {
for(let key of Object.keys(input)) {
if (keysToDelete.includes(key)) {
delete input[key];
if (Object.keys(input).length === 0) emptyKeys.push(inputKey)
}
if (typeof input[key] === 'object') {
deleteRecursive(input[key], keysToDelete, key, emptyKeys)
}
}
return emptyKeys;
}
let obj = { "mode1":{ "pool_1":[ { "id":115 }, ], "pool_2":[ { "id":116 } ], "pool_4":[ { "id":117 } ], }, "mode2":{ "pool_6":[ { "id":122 } ] }, "mode3":{ "pool_1":[ { "id":123 } ] }, "AWS":{ "cloud":[] }, "Azure":{ "cloud":[] } }
let value_array = ["pool_1"];
const emptyKeys = deleteRecursive(obj, value_array)
console.log("Obj after deletion:", obj);
console.log("Empty keys:", emptyKeys );