DarkDefender
DarkDefender

Reputation: 11

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”.

Upvotes: 0

Views: 1319

Answers (4)

Majed Badawi
Majed Badawi

Reputation: 28414

You can use .filter and .indexOf to check for the substring in each person's last name:

const persons = [
  { 'First Name': 'Dark', 'Last Name': 'Defender', Age: 26},
  { 'First Name': 'Ben', 'Last Name': 'Robbins', Age: 22},
  { 'First Name': 'John', 'Last Name': 'Beans', Age: 23}
];

const personArray = persons.filter(person => 
  person['Last Name'] && person['Last Name'].indexOf('der') !== -1
);

console.log(personArray);

Upvotes: 0

kind user
kind user

Reputation: 41893

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);

Upvotes: 1

fxnoob
fxnoob

Reputation: 176

As you said we have an array of the object(persons) like this:-

const arr = [
 { “First Name”: “Dark”, “Last Name”: “Defender”, Age: 26},
 { “First Name”: “Dark”, “Last Name”: “Defender”, Age: 26},
 .
 .
 . etc
]

// do this
const matchingObj = arr.find(el => el["Last Name"].endsWith("der")); // returns first occurence
console.log(matchingObj)

Upvotes: 0

Julia
Julia

Reputation: 704

You can use filter and includes methods

  const persons = [
    { "First Name": "Dark", "Last Name": "Defender", Age: 26 },
    { "First Name": "Carlos", "Last Name": "Defback" },
    { "First Name": "Carlos", "Last Name": "None"}
  ];
  const foundPersons = persons.filter(person =>
    person["Last Name"].includes("Def")
  );
  console.log('foundPersons: ', foundPersons)
  

Upvotes: 0

Related Questions