2

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!

3
  • What is the problem with that? Legibility? Optimization issues? Bear in mind that if there is a predefined lodash function it will very likely do the same: Cycle through the array, through each key to determine if it is null. I think that _.filter (lodash.com/docs#filter) would come useful, it "Iterates over elements of collection, returning an array of all elements predicate returns truthy for." Commented Nov 14, 2015 at 21:30
  • Agree with @adelriosantiago, there already is a lodash function for checking for null, _.null(value), which does the same thing you're doing above (just in a lodash way). Commented Nov 14, 2015 at 21:41
  • In angularJS use angular.forEach Commented Nov 14, 2015 at 21:56

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@user2994871 could you give feedback?
0

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>

1 Comment

Output should be ["pos","age"] not full objects

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.