0

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!

  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 29 '21 at 13:36
  • 1
    You cannot change property names, but you can create new properties and delete old ones, or create an entirely new object. – Pointy Aug 29 '21 at 13:37
  • @Pointy how can I do it in the new object? – thePeculiarCoder Aug 29 '21 at 13:42
  • Make a new object; you've already got code to make one object, just do the same thing with different property names. – Pointy Aug 29 '21 at 13:45
  • There is no attempt here; no sign of effort. – trincot Aug 29 '21 at 13:52
  • @Pointy I'll try to do it. – thePeculiarCoder Aug 29 '21 at 13:55

1 Answers1

1

    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))
sojin
  • 2,158
  • 1
  • 10
  • 18