Javascript 在数组对象中查找元素
我想检查对象数组中是否有某个值Javascript 在数组对象中查找元素,javascript,arrays,Javascript,Arrays,我想检查对象数组中是否有某个值 var list = [ { _id: 1, name: "foo" }, { _id: 2, name: "bar" }, { _id: 3, name: "foox" }, { _id: 4, name: "fooz" }, ]; var search = [1,25,33,4,22,44,5555,63]; list.forEach(function(element){ if(search.indexOf(element._id)
var list = [ { _id: 1, name: "foo" },
{ _id: 2, name: "bar" },
{ _id: 3, name: "foox" },
{ _id: 4, name: "fooz" },
];
var search = [1,25,33,4,22,44,5555,63];
list.forEach(function(element){
if(search.indexOf(element._id) != -1){
console.log("found");
}
});
例如,如果我有这样的东西:
[ { _id: 1,
name: foo },
{ _id: 2,
name: bar },
{ _id: 3,
name: foox },
{ _id: 4,
name: fooz },
]
var search = [1,25,33,4,22,44,5555,63]
然后我想检查search
中的一个值是否在对象数组中包含的一个对象中
var list = [ { _id: 1, name: "foo" },
{ _id: 2, name: "bar" },
{ _id: 3, name: "foox" },
{ _id: 4, name: "fooz" },
];
var search = [1,25,33,4,22,44,5555,63];
list.forEach(function(element){
if(search.indexOf(element._id) != -1){
console.log("found");
}
});
试试这个,希望这就是你想要的。如果:
var o = [{ _id: 1, name: "foo"}, { _id: 2, name: "bar"}, { _id: 3, name: "foox"}, { _id: 4, name: "fooz"}];
var search = [1, 25, 33, 4, 22, 44, 5555, 63];
试试这个:
var outPus = o.filter(function(u){
return search.some(function(t){ return t == u._id})
})
或者这个:
var outPut = [];
search.forEach(function(u){
o.forEach(function(t){
if(t._id == u) outPut.push(t)
})
})
这将返回一个ID列表,然后确定搜索数组中是否至少有一个元素在该列表中:
var found = arr.map(function (el) {
return el._id;
}).some(function (el) {
return search.indexOf(el) > -1;
});
这很有趣,因为它在找到第一个匹配项时立即跳出检查
var list = [
{ _id: 1, name: 'foo' },
{ _id: 2, name: 'bar' },
{ _id: 3, name: 'foox' },
{ _id: 4, name: 'fooz' }
];
var search = [1,25,33,4,22,44,5555,63];
此代码构建了搜索
中所有元素的列表,这些元素也在您的列表中
:
var inArr = search.filter(function(index){
return list.some(function(el){
return el._id === index;
});
});
console.log(inArr); // [1,4];
显然,您可以切换列表
和搜索
,以便获得一个数组,其中包含搜索
中引用的列表
中的元素:
var elements = list.filter(function(el){
return search.some(function(index){
return el._id === index;
});
});
console.log(elements); // [{ _id: 1, name: 'foo' },{ _id: 4, name: 'fooz' }]
下面是find方法的示例。希望这对你有帮助
// sample item array
const items = [
{ name : 'Bike', price : 100 },
{ name : 'Car', price : 3000 }
]
// find method example
const foundItem = items.find(( item )) => {
// you can put your desired condition over here to find an element from
// javascript array.
return item.name == 'Bike'
}
另外,您检查搜索数组的依据是什么?ID?是的,我不知道我是否必须循环搜索或对象…我尝试