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)的用戶。
添加回答
舉報