0

I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

2
  • what are "value pairs" in your example? it's not clear what you want to filter Commented Feb 18, 2020 at 9:52
  • Do you need a way to traverse all the keys in the JSON and check which has empty value? Commented Feb 18, 2020 at 10:07

6 Answers 6

1

filter only use for a array, not is a object.

You can try my code

let searchParams = 
    Object.keys(this.state.searchParams)
          .filter( key => this.state.searchParams[key] !== '' );

this.setState({searchParams })
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.entries and Object.fromEntries.

const filteredObject = Object.fromEntries(
    Object.entries(searchParams)
        .filter(([key, value]) => value !== "")
);

Will create anew object with all the keys for which the value was "" removed.

Comments

1

You can filter it this way with reduce method. Since it is an object, you have to combine object prototype .keys with array prototype .reduce to filter it.

const searchParams = {
  query: '',
  colors: [],
  text: '',
  legalities: '',
  setName: '',
  pageSize: 4
}

const notEmpty = Object.keys(searchParams).reduce((nonEmptyObj, currentKey) => {
  if (searchParams[currentKey] !== '') {
    nonEmptyObj[currentKey] = searchParams[currentKey];
  }
  return nonEmptyObj;
}, {})

console.log(notEmpty);

Comments

1

use Object.keys. In your case like this: var search = Object.keys(this.state.searchParams).filter(el => { // do something })

Comments

1

the most simple way is by using Object.keys method and then iterate the whole object. then check if searchParams[ele] is true and add in another object.

    var newObj = {};
    Object.keys(this.state.searchParams).forEach(ele => {
      if (searchParams[ele]) {
        newObj = { ...newObj, [ele]: searchParams[ele] };
      }
    });
    console.log(newObj); // new object generated with empty values eliminated
this.setState({searchParams:newObj})

Comments

1

If you want to filter out empty strings and strings (with white spaces only) as well, then we have trim the string and then check its length. If its string and its length is 0 after trimming, then its considered as empty and will be filtered out.

const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key => 
  !(typeof params[key] === 'string' && params[key].trim().length === 0)
)

If you don't want to trim, then:

const params = this.state.searchParams

Object.keys(this.state.searchParams).filter(key => params[key] !== '')

I would highly suggest you to not to use semicolon, as it takes space and JS can now ignore semicolon as well. Also, not to use double quotes unless required.

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.