最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get key and value of object whose values are not equal to null? - Stack Overflow

programmeradmin3浏览0评论

I have an object that looks like this:

let data = {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: null
    };

From the above object I want to generate a new object that only has key value pairs whose values are not null.

The expected result should look like this:

let newData = {
    toDate: this.state.toDate,
    fromDate: this.state.fromDate,
    options: "negative"
};

Here I have used a static example of data object, the null values may differ later. Basically I want a new object with key value pairs whose value is not null. Can anyone help me with a solution?

I have an object that looks like this:

let data = {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: null
    };

From the above object I want to generate a new object that only has key value pairs whose values are not null.

The expected result should look like this:

let newData = {
    toDate: this.state.toDate,
    fromDate: this.state.fromDate,
    options: "negative"
};

Here I have used a static example of data object, the null values may differ later. Basically I want a new object with key value pairs whose value is not null. Can anyone help me with a solution?

Share Improve this question edited Apr 23, 2019 at 11:14 Biraj Gautam asked Apr 23, 2019 at 11:10 Biraj GautamBiraj Gautam 1871 gold badge3 silver badges11 bronze badges 4
  • Use Object.keys(data) to get an array of data's keys. – user5734311 Commented Apr 23, 2019 at 11:12
  • 1 please share what you've tried and explain what's not working, and we can help to debug it. SO isn't a free code-writing service – Robin Zigmond Commented Apr 23, 2019 at 11:14
  • @RobinZigmond I tried Object.values(data).filter(item => item !== null); this but the result is not as expected as I get values only. – Biraj Gautam Commented Apr 23, 2019 at 11:18
  • 1 @BirajGautam Which function you have tried? As my answer will help you in future where you need to remove nested null values as well. Example, data = {a: { b: null }} so it will remove null as well. and in my answer if you do not want to remove empty string you can remove that condition from if. Using reducer function doesn't make sense here, as in Mayank's answer. It will consume more memory, don't think for temporary solution, think of time plexity, space plexity. And future expects as well, which will solve your many problems in future codes. – ATUL SHARMA Commented Apr 23, 2019 at 11:53
Add a ment  | 

6 Answers 6

Reset to default 6

You can try filtering Object.entries()

const data = {
  toDate: {},
  fromDate: {},
  filteredEntityText: null,
  options: 'negative',
  searchTerm: null
};

const newData = {};
Object.entries(data)
  .filter(([, value]) => value !== null)
  .forEach(([key, value]) => (newData[key] = value));

console.log(newData);

You can use for...in loop

let data = {
  toDate: 'toDate',
  fromDate: 'fromDate',
  filteredEntityText: null,
  options: "negative",
  searchTerm: null
};
let newData = {};
for(var k in data){
  if(data[k] != null)
    newData[k] = data[k];
}
console.log(newData);

You can use reduce to achieve the expected result:

let data = {
  toDate: "abc",
  fromDate: "cde",
  filteredEntityText: null,
  options: "negative",
  searchTerm: null
};

var newObj = Object.keys(data).reduce((acc, el) => {
  // removing all the key-value pairs where value=null
  if(data[el] !== null)
    acc[el] = data[el];
  return acc;
}, {})

console.log('newObj', newObj);

try this

let data = {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: null
    };

  let giveOriginal = (data){
     let originalHolder = {}
     for(let key in data){
        if(data[key]){
           originalHolder[key] = data[key]
         }
      }
    return originalHolder;
  }

 //call giveOriginal 
 giveOriginal(data)

First iterate through that array of objects using forEach,then check for data.searchTerm !== null.
This is a working solution.

class App extends React.Component {
  state = {
    toDate: new Date(),
    fromDate: new Date()
  };
  searches = [
    {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: null
    },
    {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: "microsoft"
    },
    {
      toDate: this.state.toDate,
      fromDate: this.state.fromDate,
      filteredEntityText: null,
      options: "negative",
      searchTerm: "apple"
    }
  ];
  render() {
    let results = [];
    this.searches.forEach(data => {
      if (data.searchTerm !== null) results.push(data);
    });
    console.log(results);
    return (
      <div>
        {results.map((data, index) => (
          <span key={index}>{data.searchTerm}, </span>
        ))}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

This all will help you to remove nested null items as well. Using some ES6 / ES2015: Below some example will modify data object directly or if you want to create duplicate object with removed nulls you can call functions given below it will return new object.

If you don't like to create an extra function and remove the items 'inline'.

Object.keys(data).forEach(k => (!data[k] && data[k] !== undefined) && delete data[k]);

Same, written as a function.

const removeEmpty = (data) => {
  Object.keys(data).forEach((k) => (!data[k] && data[k] !== undefined) && delete 
       data[k]);
  return data;
};

This function uses recursion to delete items from nested objects as well:

const removeEmpty = (data) => {
  Object.keys(data).forEach(k =>
    (data[k] && typeof data[k] === 'object') && removeEmpty(data[k]) ||
    (!data[k] && data[k] !== undefined) && delete data[k]
  );
  return data;
};

Same as function before but with ES7 / 2016 Object.entries:

const removeEmpty = data => {
  Object.keys(data).forEach(
    k => !data[k] && data[k] !== undefined && delete data[k]
  );
  return data;
};

Same as third example but in plain ES5:

function removeEmpty(data) {
  Object.keys(data).forEach(function(key) {
    (data[key] && typeof data[key] === 'object') && removeEmpty(data[key]) ||
    (data[key] === '' || data[key] === null) && delete data[key]
  });
  return data;
};
发布评论

评论列表(0)

  1. 暂无评论