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?
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?
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));
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]);
}
}
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);
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);