0

I have a javascript object like this:

filters = { loaderId:1111, search : '', postCategory: '', sortBy:'' }

I'd like to remove blank properties (empty string, undefined, null) but keep properties that are 0.

How can I do this with javascript, I'd have done this with lodash omit but now it's deprecated, thanks in advance!

3
  • 1
    When was omit deprecated? I can't see it in the list of deprecated methods nor does it say anything in the documentation. Commented Oct 31, 2019 at 13:21
  • It was in 5.0 I think Commented Oct 31, 2019 at 13:55
  • OK, I found it on the roadmap. It's indeed being removed. Weirdly, in favour of pick. The two work fundamentally differently, so I'm not sure removing omit is a good idea. Unless the functionality is somehow folded into pick but this is odd. Commented Oct 31, 2019 at 14:06

5 Answers 5

1

You can do

function clean(obj) {
  for (let propName in obj) { 
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName];
    }
  }
}

or, something like

const removeEmpty = obj => {
  Object.keys(obj).forEach(key => (obj[key] == null || obj[key] == undefined || obj[key] === '') && delete obj[key]);
};
Sign up to request clarification or add additional context in comments.

Comments

0

You could use this function:

function clearEmpty(obj) {
    return Object.keys(obj).reduce((acc, key) => {
        if(obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
            acc[key] = obj[key];
        }

        return acc;
    }, {});
}

I'll return a new object instead of mutating the original, in case you might need to keep it.

Comments

0

var filters = {
  loaderId: 1111,
  search: 0,
  postCategory: "",
  sortBy: ""
};

for (var prop in filters) {
  if (!filters[prop] && filters[prop] !== 0)
    delete filters[prop];
}
console.log(filters)

Comments

0

One-line solution:

 Object.fromEntries(Object.entries(input).filter(x => x[1] !==''));

Since

Object.entries = 
[
  [ 'loaderId', 1111 ],
  [ 'search', '' ],
  [ 'postCategory', '' ],
  [ 'sortBy', '' ]
]

And below returns [ 'loaderId', 1111 ]

Object.entries(input).filter(x => x[1] !=='')

And below convert it to an object:

{ 'loaderId' : 1111 }

Comments

0

omitBy is not on the roadmap to be deprecated. If you already have lodash in your project you could simply do:

_.omitBy(obj, v => v !== 0 && !v);

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.