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?
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;
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments