【问题标题】:Search javascript object to return the relevant catId搜索 javascript 对象以返回相关的 catId
【发布时间】:2021-10-08 17:35:41
【问题描述】:

我有以下 javascript 数组,我试图简单地返回 catId 以获得 id - 例如,如果我搜索 10000356id 我想返回 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.

【问题讨论】:

  • 使用查找:categoryIds.find(obj => obj.id == 10000356).catId
  • @JeremyThille NO categoryIds.find(obj => obj.id == 10000356)?.catId 因为如果 find 没有找到任何东西,它会返回 null 并且在这里你的代码会中断,因为你不检查它,你可能会尝试返回 null.catId,这是一个错误
  • 啊,我以为? 运算符只能在 Typescript 中使用,而不是在 JS 中。很高兴知道。是的,我知道,find 的结果可以为 null,所以当然要检查 nullity 之类的东西。
  • 是的,它在 js 中可用,这将防止错误的复制过去:P

标签: javascript arrays search filter javascript-objects


【解决方案1】:
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);

如果您确定 id 是唯一的,请使用 find,我认为这里就是这种情况。 find 将返回你想要的数据,如果没有找到则返回 null

【讨论】:

  • 如果你使用的js版本不支持?。可以使用一些 if like if (data) { return data.id === 10000356} else {return false}
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多