Frank Etoundi
Frank Etoundi

Reputation: 356

Checking the presence of some values in an array of hashes in jQuery or Javascript

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?

Upvotes: 1

Views: 1242

Answers (3)

Sems
Sems

Reputation: 61

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.

Upvotes: 1

Faly
Faly

Reputation: 13346

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);

Upvotes: 1

zabusa
zabusa

Reputation: 2719

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

Upvotes: 1

Related Questions