You may use Array.prototype.reduce()
over Object.keys()
const obj = {a:1, b:2, c:null, d: ''},
result = Object
.keys(obj)
.reduce((r,key) =>
(obj[key] && (r[key]=obj[key]), r),{})
console.log(result)
.as-console-wrapper{min-height:100%;}
This function will return true if there are any null values in an object.
function search(object = { }) {
const values = Object.values(object);
for (let i = 0, l = values.length; i < l; i++) {
if (values[i] === null) {
return true;
}
}
return true;
}
You can check like this:
if(obj && obj.myProp && obj.someOther){
//My code
}
Or you may do consider optional chaining:
if(obj?.myProp){
}
Note that the former will validate for all falsy values while the later would work only for null
and undefined
You can create a new object having valid values and then iterate over that object and populate your page accordingly. The below function takes in an object and returns an object which is only having valid values.
function filterObj (obj) {
const result = {};
Object.keys(obj).forEach(key => {
if (obj[key]) result[key] = obj[key];
});
return result;
}
const yourObject = {topBun: "kaiser", middle: null, bottomBun: "kaiser"}
const obj = filterObj(yourObject); // {topBun: "kaiser", bottomBun: "kaiser"}
I have a webpage that I’m loading information onto via an ajax call to a database. I’m pulling a singular object and if a specific field in that object is either null or empty I won’t populate that portion of the page. For instance, let’s say we have an object named Hamburger with fields topBun = “kaiser”, middle = null, and bottomBun = “kaiser”. I want to set each field based on these results.
In my head I’m thinking I’ll have to do an if([variable] == null){ //set variable to page}. What I’m wondering is if there is a more simple or refined way to do this?