Reputation: 177
Is there a better way to do this in lodash? I am basically trying to find all the keys that have null values.
var data = [
{ user: 'John', pos: null },
{ user: 'Tim', age: 40 },
{ user: 'Dave', age: null }
];
$scope.parsed = [];
_.each(data, function(obj) {
_.each(_.keys(obj), function(k){
if (obj[k] === null) {
$scope.parsed.push(k);
}
})
});
console.info($scope.parsed);
Output: ["pos","age"]
Thanks!
Upvotes: 2
Views: 77
Reputation: 77482
Try this
var data = [
{ user: 'John', pos: null },
{ user: 'Tim', age: 40 },
{ user: 'Dave', age: null }
];
var result = _(data)
.map(function (element) {
return _.keys(_.pick(element, _.isNull));
})
.flatten()
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Upvotes: 1
Reputation: 21005
Not sure how you define 'better', but I think this is a more functional answer - filter those elements that have a value that is null
$scope.parsed = _.filter(data, function(d) {
return (_.values(d).indexOf(null) !== -1);
}
var data = [{
user: 'John',
pos: null
}, {
user: 'Tim',
age: 40
}, {
user: 'Dave',
age: null
}];
parsed = _.filter(data, function(d) {
return (_.values(d).indexOf(null) !== -1);
});
console.log(parsed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Upvotes: 0