我有一个像这样的对象:
item: {
b: null
c: "asd"
i: 10
q: 10
s: Array [237,241]}
我还有一系列ID:
var ids = [237, 238, 239, 240, 242, 243...]
我不知道如何检查s中是否存在上述ID,然后 将这些项目保存到新数组或对象
for (var key in items) {
for (var i in items[key].s) {
//...
}
}
答案 0 :(得分:1)
if(items.s.some(el=>ids.includes(el))) alert("wohoo");
只需检查某些项ID是否包含在ids数组中。或者使用for循环:
for(var i = 0; i < items.s.length; i++){
if( ids.includes( items.s[i] )){
alert("wohoo");
}
}
答案 1 :(得分:0)
您可以使用Array.filter
和Array.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);
&#13;
答案 2 :(得分:0)
ids.filter(id => items.s.includes(id))
&#34;过滤器&#34; ids
&#34;包含&#34;的items.s
列表。
答案 3 :(得分:0)
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);