Проверьте, существует ли ключ объекта в объекте - javascript - PullRequest
1 голос
/ 05 марта 2020

Я сделал al oop, чтобы проверить, не существует ли ключ в другом объекте. Как только это условие выполняется, оно должно остановиться и перенаправить на определенный URL. Я получил работу oop, но моя проблема в том, что, как только условие будет выполнено. Это все еще продолжает l oop для остальных предметов. Это означает, что оно никогда не остановится и создает какую-то бесконечную л oop. Как я могу убедиться, что если условие (если) выполнено. l oop останавливается.

обязательный ресурс:

enter image description here

ресурсы: (первый раз пуст)

enter image description here

L oop:

// For every requiredResource check if it exist in the resources. (right now it is one)
    requiredResource.forEach((item: any) => {
        // Check if there are resources, if not go get them
        if(resources.length !== 0){
            // Resources are filled with 2 examples
            Object.keys(resources).forEach(value => {

                //if the required is not in there, go get this resource and stop the loop
                if(value !== item.name){

                    // Go get the specific resource that is missing
                    window.location.assign(`getspecificresource.com`);

                } else {

                    // Key from resource is matching the required key. you can continue
                    //continue
                }
            });
        } else {
            // get resources
            window.location.assign(`getalistwithresources.com`);
        }
    });

Ответы [ 2 ]

2 голосов
/ 05 марта 2020

Вы можете использовать some() метод массива для этого, например:

const found = requiredResource.some(({name}) => Object.keys(resources).indexOf(name) > -1)
if (!found) {
   window.location.assign(`getspecificresource.com`);
} else {
   // Key from resource is matching the required key. you can continue
   //continue
}

РЕДАКТИРОВАТЬ:

На основе обсуждения вы можно обновить ваш код следующим образом, чтобы добиться требуемого поведения, поскольку мы не можем выйти из forEach l oop:

requiredResource.some((item) => {
   // Check if there are resources, if not go get them
   if (resources.length !== 0) {
      // Resources are filled with 2 examples
      Object.keys(resources).some(value => {

         //if the required is not in there, go get this resource and stop the loop
         if (value !== item.name) {

            // Go get the specific resource that is missing
            window.location.assign(`getspecificresource.com`);
            return true;
         } else {

            // Key from resource is matching the required key. you can continue
            //continue            
            return false;
         }
      });
      return false;
   } else {
      // get resources
      window.location.assign(`getalistwithresources.com`);
      return true;
   }
});

Просто используя some() с return true, чтобы выйти из l oop здесь.

0 голосов
/ 05 марта 2020

Вы можете попробовать что-то вроде этого ...

let obj = {
  'a': 1,
  'b': 2,
  'c': 3
}
console.log(obj.a)
  Object.keys(obj).some(x=>{
    console.log(obj[x])
   return obj[x]==2
  })

И использовать оператор return, чтобы разбить l oop, это поможет?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...