How to check if the id exists in the array of ids javascript
我有一个物体,像:
1 2 3 4 5 6 | item: { b: null c:"asd" i: 10 q: 10 s: Array [237,241]} |
我还有一个ID数组:
1 | var ids = [237, 238, 239, 240, 242, 243...] |
我不知道如何检查在S中是否存在上述ID,然后将这些项保存到新数组或对象
1 2 3 4 5 | for (var key in items) { for (var i in items[key].s) { //... } } |
1 | if(items.s.some(el=>ids.includes(el))) alert("wohoo"); |
只需检查IDS数组中是否包含某些项ID。或者使用for循环:
1 2 3 4 5 | for(var i = 0; i < items.s.length; i++){ if( ids.includes( items.s[i] )){ alert("wohoo"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var item = { b: null, c:"asd", i: 10, q: 10, s: [237,241] } var ids = [237, 238, 239, 240, 242, 243]; // way number 1 for(var i = 0; i < item.s.length; i++){ if( ~ids.indexOf(item.s[i])){ console.log(item.s[i]); } } //way number 2 var myArr = item.s.filter(x => ~ids.indexOf(x)); console.log(myArr); |
1 | ids.filter(id => items.s.includes(id)) |
"过滤"
您可以使用
1 2 | 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` |
1 2 3 4 5 6 7 8 9 10 11 | 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); |