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

2019-10-18 10:35发布

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?

4条回答
来,给爷笑一个
2楼-- · 2019-10-18 11:13

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);
查看更多
乱世女痞
3楼-- · 2019-10-18 11:28

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

查看更多
该账号已被封号
4楼-- · 2019-10-18 11:34

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]);
    }
}
查看更多
冷血范
5楼-- · 2019-10-18 11:37

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

查看更多
登录 后发表回答