Find If Any Item In The Array Matches The Condition
I am new to Javascript. Now, Here I have an array which has multiple objects. So, I want to iterate it and if any of the object matches the condition then I want to return a value
Solution 1:
You can use filter function for this, which return the array on the condition
var container = [ { type: "", numberOfQuestions:"", technology:"" }, { type: "1", numberOfQuestions:"4", technology:"abcd" }, { type: "", numberOfQuestions:"6", technology:"ass" } ]
container.filter((a)=>{ return a['type'] == "" ? a : a['numberOfQuestions'] == "" ? a : a['technology'] == "" ? a : '' }).length > 0 ? true : false;
Solution 2:
You can use Array.prototype.some
var array = [...];
function validateData (array) {
return array.some(item => item.type === '' || item.numberOfQuestions === '' || item.technology === '');
}
validateData(array);
It was ES6 solution (with arrow functions).
ES5 solution:
function validateData (array) {
return array.some(function(item) {
return item.type === '' || item.numberOfQuestions === '' || item.technology === '';
});
}
Solution 3:
First off, dont use =
in the object please use :
. If you want to check the keys dynamically use this code
const validateData = (data) => {
data.map((object) => {
Object.keys(object).map((innerObj) => {
if(object[innerObj] === "") {
return true;
} else {
return false;
}
})
});
}
var obj = [{ type: "", numberOfQuestions:"", technology:"" },
{ type: "1", numberOfQuestions:"4", technology:"abcd" },
{ type: "", numberOfQuestions:"6", technology:"ass" }];
validateData(obj);
Solution 4:
This will work regardless of key names (using es6 syntax).
var data = [ { type: "", numberOfQuestions:"", technology:"" }, { type: "1", numberOfQuestions:"4", technology:"abcd" }, { type: "", numberOfQuestions:"6", technology:"ass" } ]
const checkNull = (data) => data.some(item => Object.keys(item).some(key => item[key] == ''));
console.log(checkNull(data));
Solution 5:
You can use filter method
var obj = [ { type: "", numberOfQuestions:"", technology:"" }, { type: "1", numberOfQuestions:"4", technology:"abcd" }, { type: "", numberOfQuestions:"6", technology:"ass" } ]
obj.filter((a)=>{ return a['type'] == "" ? a : a['numberOfQuestions'] == "" ? a : a['technology'] == "" ? a : '' }).length > 0 ? true : false;
Post a Comment for "Find If Any Item In The Array Matches The Condition"