Как сопоставить число с числами в массиве в vanilla JavaScript? - PullRequest
0 голосов
/ 08 октября 2018

Я делаю фильтр в JS 5.

Короче: у Bubble есть идентификаторы, атрибуты.Я беру идентификатор пузыря и сопоставляю его с массивом объектов.если идентификатор пузыря совпадает с одним из идентификатора из массива объектов, я хочу показать информацию об объекте / идентификатор.

Пользователь щелкает пузырь, а я получаю идентификатор пузыря и сохраняю его.

Затем необходимо будет сравнить идентификатор пузыря в объекте / JSON, и если идентификатор пузыря совпадает с одним из элементов в объекте, он должен отобразить идентификатор объекта и его информацию.

До сих пор мне удалось получить идентификатор объекта и числа в массиве, я думаю, но это не совсем верно.

Как я могу это исправить, чтобы, когда я щелкаю число, оно совпадало с номеромв массиве объектов и принимает соответствующий объект и отображает информацию об этом объекте?

Codepen: https://codepen.io/Aurelian/pen/xyVmgw?editors=0010

JS код:

var dataEquipmentList = [

   {
     "equipmentId": 16, 
     "equipmentTitle": "Horizontal Lifelines & Anchors",
     "equipmentMainBgImg": "https://www.yorkshirewildlifepark.com/wp-content/uploads/2016/06/lion-country-banner-1.jpg",

     "productList": [
         {  
            "rowId": 1,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                 },
                 {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                 }
               ]
         },
         {  
            "rowId": 2,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                }
            ]
          }
      ]
   },
   {
      "equipmentId": 17, 
      "equipmentTitle": "DDDDD Lifelines & Anchors",
      "equipmentMainBgImg": "http://www.waterandnature.org/sites/default/files/styles/full/public/general/shutterstock_creative_travel_projects.jpg?itok=MsZg16JU",

      "productList": [
         {  
            "rowId": 1,
            "toolList": [
                {
                  "toolPicture": "https://youtube.com/",
                  "toolName": "Tracoda",
                  "toolModelNumber": "ET 10",
                  "toolDescription": "Chest belt fitted",
                  "toolUrl": "https://google.com/"
                },
                {
                  "toolPicture": "https://youtube.com/",
                  "toolName": "Tracoda",
                  "toolModelNumber": "ET 10",
                  "toolDescription": "Chest belt fitted",
                  "toolUrl": "https://google.com/"
                }
             ]
          },
         {  
            "rowId": 2,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
               }
            ]
         }

      ]
   }
]

function getEquipmentIds() {
   for(var keys in dataEquipmentList) {
      var key = dataEquipmentList[keys];
   }
}

getEquipmentIds();


//////////
// Mindmap Code
//////////

function filterBubbles() {
   var equipmentList = document.querySelectorAll('.pt-bubble');

   equipmentList.forEach(function(item) {
      var equipmentId = item.getAttribute('data-equipment-id');

       item.addEventListener('click', function(){
            //console.log(equipmentId);

            for(var keys in dataEquipmentList) {
               var keyArray = [];
               var key = dataEquipmentList[keys].equipmentId;

              keyArray.push(keys);
               console.log(keyArray);

               for (var i=0; i < keyArray.length; i++) {        
                   if (equipmentId === keyArray[i]) {   
                       console.log(equipmentId + " It's a match with " + keyArray[0]);
                   }    
               }                
               //  if(equipmentId === keyArray) {
               //    console.log(equipmentId + "It's a match with " + key);
               // } else {
               //    console.log("else" + key);
               // }
            }  
       })        
   })
}
filterBubbles();

Ответы [ 3 ]

0 голосов
/ 08 октября 2018

Надеюсь, я вас хорошо понял, поэтому вот функция, которая возвращает запись с заданным идентификатором:

const id1 = 16;
const id2 = 17;

function match(id, list) {
  for (let item of list) {
    if (item.equipmentId === id) return item
  }
  return null
}

const dataEquipmentList = [

   {
     "equipmentId": 16, 
     "equipmentTitle": "Horizontal Lifelines & Anchors",
     "equipmentMainBgImg": "https://www.yorkshirewildlifepark.com/wp-content/uploads/2016/06/lion-country-banner-1.jpg",

     "productList": [
         {  
            "rowId": 1,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                 },
                 {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                 }
               ]
         },
         {  
            "rowId": 2,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
                }
            ]
          }
      ]
   },
   {
      "equipmentId": 17, 
      "equipmentTitle": "DDDDD Lifelines & Anchors",
      "equipmentMainBgImg": "http://www.waterandnature.org/sites/default/files/styles/full/public/general/shutterstock_creative_travel_projects.jpg?itok=MsZg16JU",

      "productList": [
         {  
            "rowId": 1,
            "toolList": [
                {
                  "toolPicture": "https://youtube.com/",
                  "toolName": "Tracoda",
                  "toolModelNumber": "ET 10",
                  "toolDescription": "Chest belt fitted",
                  "toolUrl": "https://google.com/"
                },
                {
                  "toolPicture": "https://youtube.com/",
                  "toolName": "Tracoda",
                  "toolModelNumber": "ET 10",
                  "toolDescription": "Chest belt fitted",
                  "toolUrl": "https://google.com/"
                }
             ]
          },
         {  
            "rowId": 2,
            "toolList": [
               {
                   "toolPicture": "https://youtube.com/",
                   "toolName": "Tracoda",
                   "toolModelNumber": "ET 10",
                   "toolDescription": "Chest belt fitted",
                   "toolUrl": "https://google.com/"
               }
            ]
         }

      ]
   }
]

console.log(match(id1, dataEquipmentList))
console.log(match(id2, dataEquipmentList))
0 голосов
/ 08 октября 2018

Полагаю, вам понадобится метод Array.prototype.filter().

, как его использовать:

просто измените внешний цикл for в item.addEventListener('click', function() с помощью

   let result=dataEquipmentList.filter((item)=>{
       return item.equipmentId==equipmentId;
   });
   console.log(result[0].equipmentId+'\n'+result[0].equipmentTitle);
   //17
   //DDDDD Lifelines & Anchors

это означает фильтрацию всех элементов, которые соответствуют обратному вызову, возвращающему true, из массива.Здесь может быть только один элемент, поэтому вы можете получить к нему доступ с результатом [0].Я проверил, и кажется, что он работает хорошо.

примечание: вам нужно == здесь, потому что свойства id в ваших кнопках являются строками.

или вы можете проверить метод фильтрации здесь: Array.prototype.filter () .

надеюсь, это поможет вам.

0 голосов
/ 08 октября 2018
function getMatch(data, id) {
  // Returns the object that match with the ID
  return data[data.map(i=>i.equipmentId).indexOf(id)];
}
console.log(dataEquipmentList, 16);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...