1

I have a JS object here

 {
    "test1" : "",
    "test2" : "apple",
    "test3" : "oranges",
    "test5" : ""
  }

Is there a JS one-liner that can filter out all the properties with empty strings?

Expected result:

 {
    "test2" : "apple",
    "test3" : "oranges",
  }
Jon Tan
  • 1,461
  • 3
  • 17
  • 33

3 Answers3

3

You can do this snippet:

const foo 

const bar = Object.fromEntries(Object.entries(foo).filter(value => value[1]))

In bar you have the filtered object.

To understand this, we can split it in three steps:

  • With the Object.entries(foo) we got a list of foo entries. Each entry is a array with two values, the first one is a key and the second is the value.

  • With the filter we got all entries in the entries array in the index 1 (the values) and filter if have a value. A empty string is considered a falsie value, so by using value[1] is enough.

  • For last, with Object.fromEntries we got the filtered entries and we construct a object with this entries. If there is a empty string in foo, after the filter the key value combination isn't in the fromEntries param.

1

Try this. It will delete all empty property from your original object.

const x = {
    "test1" : "",
    "test2" : "apple",
    "test3" : "oranges",
    "test5" : ""
};
Object.keys(x).filter(k => x[k] === '').map(k => delete x[k]);
console.log(x);
Dong Nguyen
  • 1,239
  • 9
  • 17
1

You can use Object.fromEntries to rebuild a new filtered object:

var obj = {
  "test1": "",
  "test2": "apple",
  "test3": "oranges",
  "test5": ""
};

obj = Object.fromEntries(Object.keys(obj).filter(k => obj[k] !== '').map(k => [k, obj[k]]));

console.log(obj);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55