4 回答
TA贡献1863条经验 获得超2个赞
您可以循环遍历数组并搜索对象。
users = [{
office: "J Limited",
contact: {
first_name: "James",
last_name: "Wilson",
address: "Canada"
}
}, {
office: "Q Limited",
contact: {
first_name: "Quin",
last_name: "Ross",
address: "Australia"
}
}, {
office: "N Limited",
contact: {
first_name: "Nancy",
last_name: "Mathew"
},
address: "England"
},
{
office: "J Limited",
contact: {
first_name: "Jacob",
last_name: "Wilson",
address: "Canada"
}
}
]
function search(searchKey) {
searchKey = searchKey.toLowerCase();
results = [];
for (var i = 0; i < users.length; i++) {
if (users[i].contact.first_name.toLowerCase().includes(searchKey) || users[i].contact.last_name.toLowerCase().includes(searchKey) || users[i].office.toLowerCase().includes(searchKey)) {
results.push(users[i]);
}
}
return results;
}
var resultObject = search("ja");
if (resultObject) {
for(i in resultObject){
console.log(resultObject[i].office, resultObject[i].contact.first_name, resultObject[i].contact.last_name)
}
}
TA贡献1875条经验 获得超3个赞
要获取匹配的用户,您可以执行以下操作:
const searchString = 'ja'
const matchingUsers = users.filter(user =>
user.office.contains(searchString) ||
user.contact.first_name.contains(searchString) ||
user.contact.last_name.contains(searchString)
)
然后您可以按照自己喜欢的方式设置匹配用户列表的格式
编辑:contains可能不适用于某些 JS 版本(适用于 Chrome),因此替换contains为includes:
const searchString = 'ja'
const matchingUsers = users.filter(user =>
user.office.includes(searchString) ||
user.contact.first_name.includes(searchString) ||
user.contact.last_name.includes(searchString)
)
TA贡献1777条经验 获得超10个赞
let users = [{
office: "J Limited",
contact: { first_name: "James", last_name: "Wilson", address: "Canada" }
}, {
office: "Q Limited",
contact: { first_name: "Quin", last_name: "Ross", address: "Australia" }
}, {
office: "N Limited",
contact: { first_name: "Nancy", last_name: "Mathew", address: "England"},
}];
// ig: i for case-insensitive, g for global
const regEx = new RegExp('ja', 'ig');
const result = users.filter(
each =>
each.office.match(regEx) ||
each.contact.first_name.match(regEx) ||
each.contact.last_name.match(regEx)
)
.map(
each => [
each.office,
each.contact.first_name,
each.contact.last_name
]
);
console.log(result);
TA贡献1829条经验 获得超13个赞
const filterUser = users.filter(user =>{ return user.office.toLowerCase().includes((searchField).toLowerCase()) });
您的 searchField 是输入的值,现在可以使用 filteruser,因为它将返回搜索中包含办公室名称的用户,或者如果在 searchField 中未输入任何内容,则返回全部。
您现在可以通过 filterUser 进行映射,以便能够使用包含输入值(即您的 searchField)的用户。
添加回答
举报