1

I want to check if a values of some key are not null or blank in an array or hashes

array = [{a:'1', b:''}, {a:'2', b:''}, {a:'3', b:null}]

Trying assert that all b are present (no blank or nil). My current approach with jQuery

function checkPresence(array){
    result = false;
    $.each(array, function (i, field) {
        if(field['b'] !== '' && field['b'] !== null){
            result = true;
            return false;
        };
    });
    return result;
}

I believe/hope jQuery and Javascript have a better solution for it, but don't know it (yet).

Can you help?

Frank Etoundi
  • 336
  • 3
  • 10

3 Answers3

1
var array = [{a:'1', b:''}, {a:'2', b:''}, {a:'3', b:null}]
array.some(item => !item.b)
// true if anything null or undefined or ""
zabusa
  • 2,520
  • 21
  • 25
1

It can be easily done with array.prototype.some :

var array = [{a:'1', b:''}, {a:'2', b:''}, {a:'', b:null}];
var res = array.some(e => e.b);
console.log(res);

var array = [{a:'1', b:''}, {a:'2', b:'something'}, {a:'', b:null}];
var res = array.some(e => e.b);
console.log(res);
Faly
  • 13,291
  • 2
  • 19
  • 37
1

You can use javascript's foreach function which is a function of array.

function checkPresence(array){

    array.foreach(function(element) {
        if(field['b'] === '' || field['b'] === null)
            return false;
    });

    return true;
}

I recommend you to check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference for more information about javascript.

Sems
  • 61
  • 1
  • 6