【问题标题】:Search for matches in an array of objects. JS在对象数组中搜索匹配项。 JS
【发布时间】:2020-07-19 17:18:59
【问题描述】:

请帮我完成任务: 我从服务器收到以下响应。我需要搜索这个答案,并依次与每个字段进行比较。

例子:

我的任务是我确定应该有 3 个对象,每个对象都有自己的类型字段值,即“API”、“DEFAULT”或“X”。怎么做才能让你在整个对象中搜索这三个值,如果缺少其中一个会报错?

{
  "result": [
    {
      "id": "54270522",
      "key": "1-16UUC93PT",
      "type": "API"
    },
    {
      "id": "54270522",
      "key": "3-1JOPPEIZI",
      "type": "DEFAULT"
    },
    {
      "id": "54270522",
      "key": "3-1JOPPEIZI",
      "type": "Х"
    }
  ],
  "success": true
}

【问题讨论】:

    标签: javascript automation cypress qa


    【解决方案1】:

    您可以先验证长度是否为 3,然后遍历所有类型并检查每个类型是否存在。

    const data = {
      "result": [
        {
          "id": "54270522",
          "key": "1-16UUC93PT",
          "type": "API"
        },
        {
          "id": "54270522",
          "key": "3-1JOPPEIZI",
          "type": "DEFAULT"
        },
        {
          "id": "54270522",
          "key": "3-1JOPPEIZI",
          "type": "Х"
        }
      ],
      "success": true
    };
    const requiredTypes = ['API', 'DEFAULT', 'Х'];
    const types = new Set(data.result.map(({type})=>type));
    const good = data.result.length === 3 && requiredTypes.every(type=>types.has(type));
    console.log(good);

    【讨论】:

    • 如果长度不是三个或者你有两次相同的类型,这将不起作用
    • @MichaelGoldenberg 我已经解决了你提到的第二个问题,但问题指定应该正好有 3 个。
    • 这个答案不正确。如果您有多次相同的类型,例如“API”、“DEFAULT”和“API”,它仍然会返回 true。即使并非所有类型都存在。
    • 大声笑,nvm。看起来我无法复制并粘贴到控制台中。继续做你正在做的事情:thumpsup:
    • @ROMANSKRIPNIKOV 没问题。
    【解决方案2】:

    如果您还想知道这 3 个值中缺少哪个值:

    const check = (obj) => {
      if (obj.result.length !== 3) return false;
    
      let validTypes = ['API', 'DEFAULT', 'X'];
    
      obj.result.forEach((r) => {
        const index = validTypes.indexOf(r.type);
    
        if (index !== -1) validTypes.splice(index, 1);
      })
    
      if (validTypes.length) return `${validTypes.join(', ')} is missing`;
    
      return true;
    };
    

    所以如果你有类似的东西:

    const test = {
      "result": [
        {
          "id": "54270522",
          "key": "1-16UUC93PT",
          "type": "API"
        },
        {
          "id": "54270522",
          "key": "3-1JOPPEIZI",
          "type": "DEFAULT"
        },
        {
          "id": "54270522",
          "key": "3-1JOPPEIZI",
          "type": "X2"
        }
      ],
      "success": true
    }
    

    你打电话给check(test),它会返回“X is missing”。如果传递给 check 函数的对象中存在所有三种类型,它将返回 true。当然,这可以根据需要进行调整。更多对象、不同类型等...

    【讨论】:

    • 谢谢!这就是我需要的!
    • @ROMANSKRIPNIKOV 如果这正是您所需要的,也请接受该答案作为官方答案
    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多