-3

For a given object if the input "value" of a property is "" , we want to delete that property from the object .

Ex

{
 "Speed": "59 MBPS",
 "latitude": "90.2",
 "longitude": ""
}

As per the example ,since the value of longitude is "" , this should get deleted from the object. Please suggest a javascript code to achieve this .

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Divya G
  • 15
  • 3

1 Answers1

1

You can use Object.keys() to get keys from the Object. Then you can filter the properties !=="" and then reduce it to form an Object.

Something like this:-

let o = {
  "Speed": "59 MBPS",
  "latitude": "90.2",
  "longitude": "",
  "prop": ""
};

let res = Object.keys(o).filter(k => o[k] !== "").reduce((acc, cv) => {
  acc[cv] = o[cv];
  return acc;
}, {});
console.log(res);

Or simply use delete like below:

let o = { "Speed": "59 MBPS", "latitude": "90.2", "longitude": "" };

for (let key in o) {
    if (o.hasOwnProperty(key) && o[key] == "") {
        delete o[key];
    }
}

console.log(o);
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37