I have the following javascript array and I am trying to simply return the catId for an id - for instance if I search for the id of 10000356 I want to return the value of 4. How should I do this?
categoryIds = [
{
"id": 10000282,
"catId": 0
},
{
"id": 10000340,
"catId": 0
},
{
"id": 10000341,
"catId": 0
},
{
"id": 10000334,
"catId": 1
},
{
"id": 10000333,
"catId": 2
},
{
"id": 10000336,
"catId": 2
},
{
"id": 10000337,
"catId": 3
},
{
"id": 10000356,
"catId": 4
}
]
categoryIds.filter(id => id == 10000356);
Expected outcome :
4 - the catId for `10000356` is the integer 4.
const result = categoryIds.find((data) => data?.id === 10000356); // beware result can be null
// use ?. to avoid error if data is null
// rembere that you have an array of object not of id ;)
console.log("the catId for 10000356 is the integer " + result?.catId);
use find if you are sure that the id are unique and I think it's the case here. find will return the data you want and return null if not found