Skip to content
Advertisement

How to get the object property and its property value if the property value is not null then transform the object property?

I have an object here that I want to get the property and property value if the the property value is not null.

var sample = {code: null, area: "Tokyo", contact: null, name: "John Doe", schedule:"Aug 29, 2021"}

Then transform the object property into

  • “area” into “location”
  • “name” into “fullName”
  • “schedule” into “date”

Is there a way to do it?

Thanks!

Advertisement

Answer

    const removeNull = (sample) => {
     let newObj = {}
     for (var key in sample) {
        if (sample[key]) {
            newObj[key] = sample[key]
        }
     }
     return newObj;
    }
    
    let sample =  {code: null, area: "Tokyo", contact: null, name: "John Doe", schedule:"Aug 29, 2021"}
    console.log(removeNull(sample))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement