为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开心每一天1111 2023-05-25 17:22:37
我有对象数组 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:falsetruefalsetrue
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您可以检查数组是否包含任何对象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) )


查看完整回答
反对 回复 2023-05-25
?
九州编程

TA贡献1785条经验 获得超4个赞

你可以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));



查看完整回答
反对 回复 2023-05-25
  • 2 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信