我没有得到搜索键背后的用例,但是下面的代码应该适合您。假设钥匙可以是任何东西,而不仅仅是姓名、性别和身份。
const arr = [
{ name:'Ferdinand Marlon', gender:'male', status:'active' },
{ name:'Acey Fe', gender:'female',status:'inactive' },
{ name:'Ferry Mario', gender:'male', status:'active' },
{ name:'Bernard Razo', gender:'male', status:'active' },
]
function getKeysInMatchesInValue(arr,searchValue){
//execute search
let keys = [];
arr.forEach((elem) => {
let arrayObjKeys = Object.keys(elem);
arrayObjKeys = arrayObjKeys.filter((k) => {
if(elem[k].toLowerCase().includes(searchValue.toLowerCase())){
return true;
}
})
keys = [...keys, ...arrayObjKeys];
})
return [...new Set(keys)]; //eliminate duplicates
}
const t1 = getKeysInMatchesInValue(arr,"Ma")
console.log(t1)
//expected result [ 'name', 'gender' ]
const t2 = getKeysInMatchesInValue(arr,"Fe")
console.log(t2)
//expected result [ 'name', 'gender' ]
const t3 = getKeysInMatchesInValue(arr,"Fer")
console.log(t3)
//expected result [ 'name' ]
const t4 = getKeysInMatchesInValue(arr,"Ber")
console.log(t4)
//expected result [ 'name' ]
const t5 = getKeysInMatchesInValue(arr,"Ac")
console.log(t5)
https://jsfiddle.net/ahedxzcs/