How to filter an array of objects with names from another array of objects [duplicate]

喜你入骨 提交于 2021-02-11 17:53:40

问题


I'm new to Javascript and I'm struggling with how to use the map, filter, find and other functions. I have two arrays of objects, and I wanted to filter the first one with the second.

const users = [ 
  { name: 'Anna', age: 22, gender: 'F' }, 
  { name: 'John', age: 25, gender: 'M' },
  { name: 'Mary', age: 27, gender: 'F' },
  { name: 'Joe',  age: 30, gender: 'M' } 
] 

const filter = [ 
  { name: 'Anna' }, 
  { name: 'John' } 
] 

// Here is the expected result:
const expected_result = [ 
  { name: 'Anna', age: 22, gender: 'F' },
  { name: 'John', age: 25, gender: 'M' } 
] 

Does anyone know what is the best way to do this?


回答1:


something like this?

const filteredUsers = users.filter(user=>filter.find(x=>(x.name==user.name)&&(x.age==user.age)&&(x.gender==user.gender));


what would be better is to give everyone a unique id.

const filteredUsers = users.filter(user=>filter.find(x=>(x.id==user.id));





回答2:


"What is the best way" is a matter of opinion, but if you would have a large filter object, then it makes sense to first convert it to a temporary set:

function filterBy(users, filter) {
    let set = new Set(filter.map(({name}) => name)); // for faster lookup
    return users.filter(({name}) => set.has(name));
}

// demo
const users = [{name: 'Anna',age: 22,gender: 'F',},{name: 'John',age: 25,gender: 'M',},{name: 'Mary',age: 27,gender: 'F',},{name: 'Joe',age: 30,gender: 'M',},];
const filter = [{name: 'Anna',},{name: 'John',}];
console.log(filterBy(users, filter));



回答3:


const users = [{
    name: 'Anna',
    age: 22,
    gender: 'F',
  },
  {
    name: 'John',
    age: 25,
    gender: 'M',
  },
  {
    name: 'Mary',
    age: 27,
    gender: 'F',
  },
  {
    name: 'Joe',
    age: 30,
    gender: 'M',
  },
];

const filter = [{
    name: 'Anna',
  },
  {
    name: 'John',
  },
];

const result = users.filter(value => {
  const isExist = filter.findIndex(data => data.name === value.name);
  return isExist === -1 ? false: true;
});

console.log(result)


来源:https://stackoverflow.com/questions/64030984/how-to-filter-an-array-of-objects-with-names-from-another-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!