分享
三行代码  ›  专栏  ›  技术社区  ›  Josh

编写了一个函数来测试数组中每个对象的特定键,即使键存在,也会不断地变为false

  •  0
  • Josh  · 技术社区  · 1 周前

    我已经编写了一个函数来检查每个对象,但是不管怎样,我总是得到false,即使我为每个对象添加了一个存档密钥,我也不确定我做错了什么。

    Codesandbox 样品:

        const hasArchived = (groupItems) => {
          let answer;
    
          for (let i = 0; i < groupItems.length; i++) {
            groupItems[i].hasOwnProperty("archived")
              ? (answer = true)
              : (answer = false);
          }
    
          return answer;
        };
    

    这是groupItems数据集的一个示例:

    [
     [
       {
         name: 'item 1'
         groupName: 'Marvel Characters'
         archived: false
       },
       {
         name: 'item 2'
         groupName: 'Marvel Characters'
         archived: true
       },
       {
         name: 'item 3'
         groupName: 'Marvel Characters'
         archived: false
       }
     ],
     [
       {
         name: 'item 1'
         groupName: 'DC Characters'
         archived: false
       },
       {
         name: 'item 2'
         groupName: 'DC Characters'
         archived: true
       },
       {
         name: 'item 3'
         groupName: 'DC Characters'
         archived: false
       }
     ]
    ]
    
    1 回复  |  直到 1 周前
        1
  •  0
  •   Guerric P    1 周前

    这是因为你的数组有两层深度,你也可以使用 Array.prototype.some 对于此用例:

    const data = [
     [
       {
         name: 'item 1',
         groupName: 'Marvel Characters',
         archived: false
       },
       {
         name: 'item 2',
         groupName: 'Marvel Characters',
         archived: true
       },
       {
         name: 'item 3',
         groupName: 'Marvel Characters',
         archived: false
       }
     ],
     [
       {
         name: 'item 1',
         groupName: 'DC Characters',
         archived: false
       },
       {
         name: 'item 2',
         groupName: 'DC Characters',
         archived: true
       },
       {
         name: 'item 3',
         groupName: 'DC Characters',
         archived: false
       }
     ]
    ];
    
    const hasArchived = groupItems => groupItems.some(x => x.some(({ archived }) => archived));
    
    
    console.log(hasArchived(data));