'Search for matches in an array of objects. JS

I have the following response from the server. I need to search this answer and compare it in turn with each field.

Example:

My task is that I know for sure that there should be 3 objects and each object has its own value for the type field, this is 'API', 'DEFAULT' or 'X'. How can you make it so that you can search for these three values ​​in the whole object and get an error if one of them is missing?

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



Solution 1:[1]

You can first verify that the length is 3 and then loop over all the types and check if each one is present.

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);

Solution 2:[2]

In case you would like to also know which value of those 3 are missing:

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;
};

So if you would have something like:

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
}

and you call check(test) it will return "X is missing". If all three types are present in the object that gets passed into the check function, it will return true. Of course this can be adjusted as you need. More objects, different types etc...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Devchris