Skip to content
Advertisement

how to return boolean value based on condition check in array object javascript

I have object array obj1, obj2,

if the name of object cannot have All key name return true

if the name of object can have only one All key name and other object return false

if the name of object can have only one All key name and no other object return true

if the name of object has too many key name All return false

based on above conditions how to do in javascript.

function checkObj(ob){
  var result = ob.filter(e=>e.name=="All");
  if(result.length !== 1){
    return false;
  }
  else{
    return true;
  }
}

var  obj1=[
  {id:1, name: "All", value:"all"},
  {id:2, name: "Sun", value:"sun"},
  {id:3, name: "Mon", value:"mon"},
]

var  obj2=[
  {id:4, name: "Thur", value:"thur"},
  {id:8, name: "Mon", value:"mon"},
]

var  obj3=[
  {id:1, name: "Thur", value:"thur"},
  {id:5, name: "All", value:"all"},
  {id:2, name: "Mon", value:"mon"},
  {id:6, name: "All", value:"all"}
]

var obj4=[
{id:1, name: "All", value:"all"}
]

var r1= this.checkObj(obj1);
var r2=this.checkObj(obj2);
var r3=this.checkObj(obj3);
var r4=this.checkObj(obj4);

Expected Output:

false
true
false
true

Advertisement

Answer

You can check if the array has any objects with name = "All".

Then, return true if

  • The array has name = "All" object and the array’s length is 1
  • or the array doesn’t have name = "All"
function checkObj(arr) {
  const hasAll = arr.some(o => o.name === "All")
  return (arr.length === 1 && hasAll) || !hasAll
}

Here’s a snippet:

function checkObj(arr) {
  const hasAll = arr.some(o => o.name === "All")
  return (arr.length === 1 && hasAll) || !hasAll
}

const obj1=[{id:1,name:"All",value:"all"},{id:2,name:"Sun",value:"sun"},{id:3,name:"Mon",value:"mon"},],
    obj2=[{id:4,name:"Thur",value:"thur"},{id:8,name:"Mon",value:"mon"},],
    obj3=[{id:1,name:"Thur",value:"thur"},{id:5,name:"All",value:"all"},{id:2,name:"Mon",value:"mon"},{id:6,name:"All",value:"all"}],
    obj4=[{id:1,name:"All",value:"all"}];

console.log( checkObj(obj1) )
console.log( checkObj(obj2) )
console.log( checkObj(obj3) )
console.log( checkObj(obj4) )
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement