Check If Any Of The Specific Key Has A Value In Javascript Array Of Object
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 t
Solution 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}];
constcheck = arr => arr.map(v => !!v.file);
console.log(check(myArray));
Solution 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]);
}
}
Solution 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);
Solution 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);
Post a Comment for "Check If Any Of The Specific Key Has A Value In Javascript Array Of Object"