Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how _.compact(array)
removes falsey elements fr
Another approach
const objFilter = (obj, condition) => {
let newObj = {}
for (const [key, value] of Object.entries(obj)) {
if (condition(value)) {
newObj = { ...newObj, [key]: value }
}
}
return newObj
}
Fire like this:
const newData = objFilter(oldData, (value) => value.marked === false)
Unfortunately I cannot direclty comment on the posts above yet, so I create this extra post.
Since Lodash v4 the functionality described above has been moved to _.pickBy. With _.identity
as default you could also change your code to:
var filtered = _.pickBy(obj);
See this JSBin for a working example.
let temp = {
propA: true,
propB: true,
propC: false,
propD: true,
}
let obj = {}
for(x in temp){
if(temp[x] == true){
obj[x] = temp[x]
}
}
console.log(obj)
Using for-in loop we can achieve it something like this.
From lodash 4, we can use pickBy() to get only the value equal to true.
const active = _.keys(_.pickBy(object));
Here are two vanilla javascript options:
A.: Iterate over the object's keys and delete those having a falsey value.
var obj = {
propA: true,
propB: true,
propC: false,
propD: true,
};
Object.keys(obj).forEach(key => {
if (!obj[key]) delete obj[key];
});
console.log(obj);
See Object.keys()
and Array.prototype.forEach()
B.: Iterate over the object's keys and add truthy values to a new object.
var obj = {
propA: true,
propB: true,
propC: false,
propD: true,
};
var filteredObj = Object.keys(obj).reduce((p, c) => {
if (obj[c]) p[c] = obj[c];
return p;
}, {});
console.log(filteredObj);
See Object.keys()
and Array.prototype.reduce()
You want _.pick
, it takes a function as an argument and returns an object only containing the keys for which that function returns truthy. So you can do:
filtered = _.pick(obj, function(value, key) {return value;})
Or even more succinctly:
filtered = _.pick(obj, _.identity)
Lodash 4.0 split the _.pick
function into _.pick
, which takes an array of properties, and _.pickBy
which takes a function. So now it'd be
filtered = _.pickBy(obj, function(value, key) {return value;})
Or, since _.pickBy
defaults to using _.identity
as it's second argument, it can just be written as:
filtered = _.pickBy(obj);