[英]JavaScript: find objects in array with property containing a specific string
In JavaScript, if you have an array of objects with a format like:在 JavaScript 中,如果您有一个对象数组,其格式如下:
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'.并且您需要逐一查找姓氏中带有特定字符串的人,例如:'der'。
How would you use the .find()
to find and return the persons with 'der' in their last name?您将如何使用
.find()
查找并返回姓氏中带有 'der' 的人?
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”.它适用于年龄,但我似乎无法为多个单词键(如“姓氏”)提供正确的语法。
You could use Array#filter
to filter out all of these entries where Last Name
includes "der"
.您可以使用
Array#filter
过滤掉Last Name
包含"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);
You can use .filter
and .indexOf
to check for the substring in each person's last name:您可以使用
.filter
和.indexOf
来检查每个人姓氏中的子字符串:
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);
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)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.