0

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

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response. I tried this method too and it also gives me a “TypeError: Cannot read property ‘includes’ of null”
@DarkDefender Updated answer.
0

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)
  

Comments

0

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)

Comments

0

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

2 Comments

Thank you for the response. Using this method gives me a “TypeError: Cannot read property ‘indexOf’ of null”
Make sure every object has a 'Last Name' property as above. Yoi can also check if person['Last Name'] exists before the comparison

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.