-5

I have an array of objects, where I want to see if the "value" for a "key" in any of the objects is "null". i.e:

var array = 
[{name:{} address : "something"},
{name:null address : "something2"},
{name:{} address : "something23"}]

In the above I want to check if any of the name object is null, return false

Can anyone help or direct to the appropriate sources?

user1234
  • 3,000
  • 4
  • 50
  • 102

2 Answers2

4

Use Array's some().

var data = [
  { name: ..., value: ... },
  ...
];
var hasUndefinedName = data.some(e => e.name===null || e.name===undefined);

Or, with older ES5 syntax:

...
var hasUndefinedName = data.some(function(e) {
  return (e.name===null || e.name===undefined);
});

And of course if the intention is to remove elements with undefined name, use Array's filter():

var data = [
  { name: ..., value: ... },
  ...
];
var filtered = data.filter(e => e.name!==null && e.name!==undefined);
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • 'Pomax' : is array.some available in IE9+? – user1234 Jun 11 '16 at 21:19
  • 1
    Yes. http://caniuse.com and http://kangax.github.io/compat-table - your friend in all matters compatibility. Also note that Microsoft has now, finally, officially and irrevocable ceased support for all versions of Internet Explorer that aren't IE11 or EDGE with the exception of IE9 for, specifically, Windows Vista SP2 users. Anyone else will not get **any** updates anymore for older versions of IE, and they're on their own. The right thing to do would be to follow Microsoft here and stop supporting literally dead browsers (you don't support Firefox 3.6 or Safari 3 either, for example) – Mike 'Pomax' Kamermans Jun 11 '16 at 21:22
1

This is what you need:

var bool = false;
array.forEach(item => {
    bool = bool || Object.keys(item).some(key => item[key] == null);
});

If bool equals true then there is at least 1 element in the array that has a property equal to null;

I put == sign instead of === intentionally, since == null checks for both null and undefined.

Azamantes
  • 1,435
  • 10
  • 15