如何检查id是否存在于ids javascript数组中

新手上路,请多包涵

我有一个像这样的对象:

 item: {
    b: null
    c: "asd"
    i: 10
    q: 10
    s: Array [237,241]}

我还有一个 id 数组:

 var ids = [237, 238, 239, 240, 242, 243...]

我不知道如何检查上面的 id 是否存在于 s 中,然后将这些项目保存到新的数组或对象中

        for (var key in items) {
            for (var i in items[key].s) {
        //...
            }
        }

原文由 wezeweze 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 491
2 个回答
 if(items.s.some(el => ids.includes(el))) alert("wohoo");

只需检查 ids 数组中是否包含某些项目 id。或者使用 for 循环:

 for(var i = 0; i < items.s.length; i++){
 if( ids.includes( items.s[i] )){
  alert("wohoo");
 }
}

原文由 Jonas Wilms 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 Array.filterArray.indexOf 。我假设您没有使用任何代码转换器,我建议您使用 indexOf 而不是 includes 因为它具有更好的浏览器支持。

 var foundIds = item.s.filter(x => ids.indexOf(x) !== -1);
// foundIds now contains the list of IDs that were matched in both `ids` and `item.s`

 var item = {
    b: null,
    c: "asd",
    i: 10,
    q: 10,
    s: [237,241]
}
var ids = [237, 238, 239, 240, 242, 243];

var foundIds = item.s.filter(x => ids.indexOf(x) !== -1);
console.log(foundIds);

原文由 XCS 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题