根据值数组中的值查找对象数组中的对象 - Javascript

时间:2018-04-17 17:29:26

标签: javascript arrays object

说我有阵列

const idArray = ["935", "933", "930"];

我想获得具有与idArray

中的一个值匹配的id属性的对象
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"
  },
]

所以在这种情况下,我想返回名称为KevinVanessaVictor的对象。

3 个答案:

答案 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;
&#13;
&#13;