We have an array of objects like:
const persons = [{
    name: "john",
    age: 23
}, {
    name: "lisa",
    age: 43
}, {
    name: "jim",
    age: 101
}, {
    name: "bob",
    age: 67
}];
And an array of a attribute values of the objects in object
const names = ["lisa", "bob"]
How can we find persons with name in the names array using es6, like:
const filteredPersons = [{
    name: "lisa",
    age: 43
}, {
    name: "bob",
    age: 67
}];
                ES6
Use filter function with predicate and in it check the existence of the name in the names array.
const persons = [
    {name: "john", age:23},
    {name: "lisa", age:43},
    {name: "jim", age:101},
    {name: "bob", age:67}
];
const names = ["lisa", "bob"];
const filtered = persons.filter(person => names.includes(person.name));
console.log(filtered);
You can use filter() and inlcudes() to get required result.
DEMO
const persons = [{
  name: "john",
  age: 23
}, {
  name: "lisa",
  age: 43
}, {
  name: "jim",
  age: 101
}, {
  name: "bob",
  age: 67
}];
const names = ["lisa", "bob"];
console.log(persons.filter(({
  name
}) => names.includes(name)))
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With