Home > Mobile >  How to get index of multiple IDs in response
How to get index of multiple IDs in response

Time:10-23

The following code gets an index of specific ID in response. It works fine when ID is the 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