我有以下javascript数组,我试图简单地返回catId
的id
-例如,如果我搜索10000356
的id
,我想返回4
的值。我该怎么做呢?
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);
预期结果:
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);
使用find如果你确定id是唯一的,我认为这是这种情况。Find将返回所需的数据,如果未找到则返回null