Home > Back-end >  How to Get Index of multiple IDs in response in javascript
How to Get Index of multiple IDs in response in javascript

Time:10-22

I Have Following Code To get index of Specific Id in response. this code works fine when Id is only one. But Now I have 3 IDs. so what to do to get multiple index of multiple IDs

 function getIndex(CategoryID) {
          return response.responseContents.findIndex(
            (obj) => obj.CategoryID === CategoryID,
          );
        }

        const index = getIndex(CategoryToGetName);

CodePudding user response:

You can do a simple for loop where you populate an array with the matched indexes.

let idxs = [];
for (let i in response.responseContents) {
 if (response.responseContents[i] == CategoryID) idxs.push(parseInt(i));
}
return idxs;

CodePudding user response:

You could do something like:

function getIndex(CategoryID)
{
   return response.responseContents.map((obj, index) => {
       if (obj.CategoryID === CategoryID)
           {
                return index;
           }
   }
}

const index = getIndex(CategoryToGetName);

CodePudding user response:

Please try below code

findIndex(CategoryIDS){
     return response.responseContents.filter((r,index)=>
       if(CategoryIDS.indexOf(r.CategoryID)>-1){
         return index;
       }
     )
}
  • Related