JavaScript: find objects in array with property containing a specific string

In JavaScript, if you have an array of objects with a format like:

Persons = {
  'First Name': 'Dark',
  'Last Name': 'Defender',
  Age: 26
}

And you need to go through each to find the persons with a certain string in their last name, for example: ‘der’.

How would you use the .find() to find and return the persons with ‘der’ in their last name?

I have tried:

personArray = persons.find(({[“Last Name”]}) => “Last Name” === ‘der’);

It works for age but I can’t seem to get the syntax right for multiple word key like “Last Name”.

Answer

You could use Array#filter to filter out all of these entries where Last Name includes "der".

const arr = [
   { "First Name": 'Dark', "Last Name": 'Defender', Age: 26},
   { "First Name": 'Dark', "Last Name": 'Abc', Age: 26},
   { "First Name": 'Dark', "Last Name": 'Xyz', Age: 26},
];

const res = arr.filter(({ ["Last Name"]: name }) => name && name.includes('der'));

console.log(res);