user2994871
user2994871

Reputation: 177

node/angular js how to find null attributes in an array of objects

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

Answers (2)

Oleksandr T.
Oleksandr T.

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

Simon H
Simon H

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

Related Questions