Check if any of the specific key has a value in Ja

2019-10-18 10:54发布

问题:

I want to Check if any of the specific key has a value in JavaScript array of object.

myArray = [ {file:null}, {file:hello.jpg}, {file:null}] ;

The key file has value so return true otherwise false. How to check this programmatically?

回答1:

Since null is a falsy value you could use double negation to check if it contains a value or it's empty (null).

let myArray = [ {file:null}, {file:'hello.jpg'}, {file:null}];

const check = arr => arr.map(v => !!v.file);

console.log(check(myArray));



回答2:

Try this:

var myArray = [ {file: null}, {file: 'hello.jpg'}, {file: null}];
for(var i = 0; i < myArray.length; i++) {
    if(myArray[i].file != null) {
        console.log(myArray[i]);
    }
}


回答3:

Use Array.prototype.some() to test if any elements of an array match a condition.

myArray = [{
  file: null
}, {
  file: "hello.jpg"
}, {
  file: null
}];
var result = myArray.some(e => e.file);
console.log(result);



回答4:

You want to take a look at map/filter/reduce, there's lots of explanations onlne, like https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209

in your case, you want to map:

items = myArray.map(item => !!item.file);