说我有阵列
const idArray = ["935", "933", "930"];
我想获得具有与idArray
const objectsArray= [
{
name: "Kevin",
color: "red",
id: "935"
},
{
name: "Ana",
color: "white",
id: "815"
},
{
name: "Maria",
color: "silver",
id: "035"
},
{
name: "Victor",
color: "red",
id: "935"
},
{
name: "Vanessa",
color: "red",
id: "933"
},
]
所以在这种情况下,我想返回名称为Kevin
,Vanessa
和Victor
的对象。
答案 0 :(得分:4)
您可以根据idArray
进行过滤。如果两个数组都很大,这可能会很慢,因为每次都需要查看idArray
:
const objectsArray= [{ name: "Kevin", color: "red", id: "935"},{ name: "Ana", color: "white", id: "815"},{ name: "Maria", color: "silver", id: "035"},{ name: "Victor", color: "red", id: "935"},{ name: "Vanessa", color: "red", id: "933"},]
const idArray = ["935", "933", "930"];
let res = objectsArray.filter(o => idArray.includes(o.id))
console.log(res)
答案 1 :(得分:0)
是的,实际上使用过滤器很容易实现。
const idArray = ["935", "933", "930"];
const objectsArray = [
{
name: "Kevin",
color: "red",
id: "935"
},
{
name: "Ana",
color: "white",
id: "815"
},
{
name: "Maria",
color: "silver",
id: "035"
},
{
name: "Victor",
color: "red",
id: "935"
},
{
name: "Vanessa",
color: "red",
id: "933"
},
];
function getObjectsInArray(objectsArray, idsArray){
return objectsArray.filter(o=>{
return idsArray.indexOf(o.id) !== -1;
})
}
console.log(getObjectsInArray(objectsArray, idArray))
答案 2 :(得分:0)
const objectsArray= [{ name: "Kevin", color: "red", id: "935"},{ name: "Ana", color: "white", id: "815"},{ name: "Maria", color: "silver", id: "035"},{ name: "Victor", color: "red", id: "935"},{ name: "Vanessa", color: "red", id: "933"},]
console.log(find(objectsArray));
function find(objArray){
const idArray = ["935", "933", "930"];
var results = [];
for(var i = 0; i < objArray.length; i++){
if(idArray.includes(objArray[i].id)){
results.push(objArray[i]);
}
}
return results;
}
&#13;