如何根据数组对象javascript中的条件检查返回布尔值

我有对象数组 obj1,obj2,


如果对象名称不能有All键名则返回 true


如果对象名只能有一个All键名,其他对象返回false


如果对象的名称只能有一个All键名且没有其他对象返回 true


如果对象的名称有太多键名All返回 false


基于以上条件如何在 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


开心每一天1111
浏览 145回答 2
2回答

潇潇雨雨

您可以检查数组是否包含任何对象name = "All"。那么,return true如果数组有name = "All"对象,数组的长度是1或者数组没有name = "All"function checkObj(arr) {  const hasAll = arr.some(o => o.name === "All")  return (arr.length === 1 && hasAll) || !hasAll}这是一个片段: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) )

九州编程

你可以Array#every在计数超过一时短路。function checkArray(array) {    return array.every((count => ({ name }) => (count += name === "All") < 2)(0));}var array1 = [{ id: 1, name: "All", value: "all" }, {  id: 2, name: "Sun", value: "sun" }, { id: 3, name: "Mon", value: "mon" }],    array2 = [{ id: 4, name: "Thur", value: "thur" }, { id: 8,  name: "Mon", value: "mon" }],    array3 = [{ id: 1, name: "Thur", value: "thur" }, { id: 5, name: "All",  value: "all" }, { id: 2, name: "Mon",  value: "mon" }, { id: 6, name: "All", value: "all" }];console.log(checkArray(array1), checkArray(array2), checkArray(array3));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript