How can I receive all values that correspond to a search list

Asked

Viewed 55 times

0

Hello,

I have the following list of objects:

0:
id: 1
firstName: Pedro
lastName: Silva
code: AA
1:
id: 2
firstName: Maria
lastName: Lurdes
code: AB
2:
id: 3
firstName: Joao
lastName: Silva
code: BA

After filling a list with the Ids I want to recover

match = [1,3]

How can I recover objects with Ids "1" and "2 in a new object"?

At the moment I have the following code:

let match = totalObjs.filter((current) => current.id == matches);

Right now if just looking for an ID works but it’s not what I need... The intended objective is the following:

0:
id: 1
firstName: Pedro
lastName: Silva
code: AA
2:
id: 3
firstName: Joao
lastName: Silva
code: BA

I appreciate any help.

2 answers

1

You can swap the comparison for a check if the id index in the array is different from -1 (which is the return in case there is no):

console.log([1,2,3].indexOf(1) != -1)
console.log([2,3].indexOf(1) != -1)

There are other filter functions that can be used, but this is the simplest way

0

Hello I would wear so.

let result = [
  {
    id: 1,
    firstName: 'Pedro',
    lastName: 'Silva',
    code: 'AA',
  },
  {
    id: 2,
    firstName: 'Maria',
    lastName: 'Lurdes',
    code: 'AB',
  },
  {
    id: 3,
    firstName: 'Joao',
    lastName: 'Silva',
    code: 'BA',
  }
]

let myBusca = function(list, propert){
  let listFilter = [];
  listFilter.push(result.map(current => {
    if(list.indexOf(current[propert]) !== -1){
      return current;
    }
  }))
  return listFilter;
}
console.log(myBusca([1, 3], 'id'));
console.log(myBusca(['AA', 'BA'], 'code'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.