Beginner in javascript so please bear with me.
I'm trying to create a program that will check an object for any null, empty or undefined values. It seems to be working fine for most part, but when there is an array in the object, it shows it as "empty items" when it is populated.
Could someone show me how to alter my code so that it checks if arrays are truly empty?
My code is as follows:
const myObj =
{ "tags": ["A", "B", "C"],
"shared_with": ["abc", "123"],
"list": [],
"public_jobs": true,
"config": null,
"id": 9406,
"name": "",
}
const removeNotEmpty = (obj) => {
Object.keys(obj).forEach(k => {//for each property of the object
if(typeof obj[k] === 'object' && obj[k] !== null){//if the property is an object
removeNotEmpty(obj[k]);//recurse
}else if(obj[k]){//if property is truthy
delete obj[k];//remove it from the object
}else if(obj[k] == !obj.length){
delete obj[k];
}
});
return obj;
};
// make sure to copy the object if you don't want to modify the first
// (that's what the Object.assign is for)
console.log(removeNotEmpty(Object.assign({},myObj)));
Thanks in advance.
EDIT: So I've incorporated some edits into my codes based on the suggestions below and this is my code now
const myObj =
{ "tags": ["A", "B", "C"],
"shared_with": ["abc", "123"],
"list": [],
"public_jobs": true,
"config": null,
"id": 9406,
"name": "",
}
const removeNotEmpty = (obj) => {
Object.keys(obj).forEach(k => {//for each property of the object
if(Object.prototype.toString.call(obj[k]) === '[object Array]'){
delete obj[k];
}else if(typeof obj[k] === 'object' && obj[k] !== null){//if the property
IS an object
removeNotEmpty(obj[k]);//recurse)
}else if(obj[k]){//if property is truthy
delete obj[k];//remove it from the object
}
});
return obj;
};
console.log(removeNotEmpty(Object.assign({},myObj)));//make sure to copy the
object if you don't want to modify the first (that's what the Object.assign
is for)
The problem now is that it does not display empty arrays, such as the "list: []" ? Any ideas people?
Object.assignto "copy the object as you don't want to modify it". In the recursive calls, you ignore that though.obj[k] == !obj.length? This will never return true even for arrays.removeNotEmptydo?