我有一个员工数组,并为每个员工分配了一些元素。
下面的数组示例:
var employees = [
{"name":"Johhny Test","salary":"1","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e8ebeac9b8bbbaa7eae6e4" rel="noreferrer noopener nofollow">[email protected]</a>"},
{"name":"Mike Milbury","salary":"10","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27161f131f1e12674f43544d4f41540944484a" rel="noreferrer noopener nofollow">[email protected]</a>"}
];
我有一种收集员工姓氏的方法,并将其存储在一个变量中。我希望能够搜索此变量中包含的姓氏的索引,以便我知道在数组中的哪个位置进行匹配。
例如,这个数组的大小可能是 100 个项目。理想情况下,我想知道姓“johnson”的人位于该数组的第 50 位。这样,我就可以从数组中的第 50 位获取与他们的记录相关的工资和电子邮件。
到目前为止我得到的代码是这样的:
var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);
但这不起作用 - 我的控制台正在记录 -1,表明它不存在于数组中。有没有一种方法可以指定要搜索的数组元素?
几乎就像 employees(name).indexOf(lname)
一样,它针对 name 元素进行搜索?
或者我的做法是错误的,也许有一种更简单、不那么困惑的方法来实现这一点?
最佳答案
您可以使用.findIndex
:
const employees = [
{"name":"Johhny Test","salary":"1","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4f4c4d6e1f1c1d004d4143" rel="noreferrer noopener nofollow">[email protected]</a>"},
{"name":"Mike Milbury","salary":"10","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b0a030f03020e7b535f4851535d4815585456" rel="noreferrer noopener nofollow">[email protected]</a>"}
];
const lastName = "Test";
const index = employees.findIndex(employee => {
const { name = '' } = employee;
const nameParts = name.split(' ');
const lname = nameParts[nameParts.length-1];
return lastName === lname;
});
console.log(index);
console.log(employees[index]);
关于javascript - 在 jQuery 数组中查找每个对象有多个元素的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65379256/