【问题标题】:How to check if each objects in array contains certain value如何检查数组中的每个对象是否包含某个值
【发布时间】:2022-01-18 19:54:39
【问题描述】:

我需要检查数组中的每个对象是否包含某个相同的值。 我可以用 for 循环来做,但我想知道是否可以用一行代码来做。 假设我有对象

    employees = [
           {
            n: 'case 1',
            date: '2021-05-4',
            id: '123',
            user: [{name: 'Vlad', id: '1'}, {name: 'Misha', id: '2'}],
            isPresent : true,
           },
           {
            caseName: 'case 2',
            date: '2021-05-4',
            id: '123',
            user: [{name: 'Alina', id: '3'}, {name: 'Alex', id: '4'}],
            isPresent : true,
           },
           {
            caseName: 'case 3',
            date: '2021-05-4',
            id: '123',
            user: [],
            isPresent : true,
           },
        ]

我的任务是检查是否所有员工都在场,所以如果isPresent 为每个对象分配true 属性,我需要获取true。 但是必须要像这样的生活来做到这一点

let employeesPresent = employees(item => item.isPresent === true); ​

【问题讨论】:

    标签: node.js reactjs react-native


    【解决方案1】:

    你可以只使用数组的every方法,它测试数组中的所有项目是否通过提供的函数实现的测试:

    let employeesPresent = employees.every(item => item.isPresent === true); ​
    

    (请注意,您在数组声明中使用 isPesent 属性,但在函数中使用 isPresent

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 2014-07-27
      相关资源
      最近更新 更多