lodash:标识json的某些字段是否超过1个项目

时间:2019-07-09 19:15:20

标签: lodash

我使用以下格式的json。我试图遍历json的每个对象,并检查subject和sport参数。如果没有一个对象不超过一个主题或一项运动,则必须返回true。如果至少一个对象具有至少一项属性(主题或运动)超过一项,那么我必须返回false

[
  {
    "id": "1",
    "name": "peter",
    "subject": [
      {
        "id": "1",
        "name": "maths"
      },
      {
        "id": "2",
        "name": "social"
      }
    ],
    "sport": [
      {
        "id": "1",
        "name": "football"
      }
    ]
  },
  {
    "id": "2",
    "name": "david",
    "subject": [
      {
        "id": "2",
        "name": "physics"
      },
      {
        "id": "3",
        "name": "science"
      }
    ],
    "sport": [
      {
        "id": "2",
        "name": "soccer"
      }
    ]
  },
  {
    "id": "3",
    "name": "Justin",
    "subject": [
    ],
,
    "sport": [
    ]
  }
]

我以下面的方式尝试过,但即使一个对象没有任何主题或运动,它也返回true

if(find(this.gridData, function(o) { return o.subject.length <= 1; }) && 
   find(this.gridData, function(o) { return o.sport.length <= 1; })  
  ){
    return true;
}
else{
  return false;
}

1 个答案:

答案 0 :(得分:0)

使用Array.every()或lodash的_.every()检查属性的长度是否符合条件。当谓词返回false时,every循环将结束,并返回false

const arr = [{"id":"1","name":"peter","subject":[{"id":"1","name":"maths"},{"id":"2","name":"social"}],"sport":[{"id":"1","name":"football"}]},{"id":"2","name":"david","subject":[{"id":"2","name":"physics"},{"id":"3","name":"science"}],"sport":[{"id":"2","name":"soccer"}]},{"id":"3","name":"Justin","subject":[],"sport":[]}]

const result = arr.every(({ subject, sport }) =>
  subject.length <= 1 && sport.length <= 1
)

console.log(result)