I'm having a strange problem with my code. There is an object that comes from an API call where videos are stored and I need to add the number of videos on the website. But sometimes there can be "null" coming from API call and obviously, I don't have to show the length of the null value.
As I wrote this code which works when I try on editors, but when I use it on my project it gives an error Cannot convert undefined or null to object. Can anyone give me an idea or hint of what I'm doing wrong? And sorry if I explained unclearly, this is my very first post here. Thank you!
const object = {
background_video: null,
vimeo_branded: 'video url',
vimeo_unbranded: "video url"
}
const removeFalsyElement = object => {
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};
console.log(removeFalsyElement(object)) // output should be 2.
The Object.keys method expects an object always. if we pass null we would get the above mentioned error
const removeFalsyElement = (object = {}) => {//default value for object in case it is null. Object.keys needs an object always
let sum = 0;
Object.keys(object).forEach(key => {
if (object[key]) {
sum += 1;
}
});
return sum;
};