1

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?

5 Answers 5

2

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%;}

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use JS filters:

const obj = {a:1, b:2, c:null, d: ''},

result = Object.fromEntries(
    Object.entries(obj).filter(([,v]) => v)
);

console.log(result)

Comments

0

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;
}

Comments

0

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

1 Comment

@evolutionxbox yes that would validate if both myProp and someOther in obj are not null and non-undefined.
0

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.