我正在尝试将文本与嵌套数组中的值匹配。但是,我需要从数组中得到的结果是角色ID。例如。我有一个名为HR Admin的文本,现在我想在“角色”对象下搜索该对象并返回ID为“ 4”
这是我的代码
数组
{
"genders": null,
"races": null,
"titles": null,
"maritalStatus": null,
"nationality": null,
"identityTypes": null,
"roles": {
"1": "System Admin",
"2": "Internal Account Manager",
"3": "CAT Manager",
"4": "HR Admin",
"5": "HR Manager",
"6": "HR Recruiter",
"7": "Candidate",
"8": "Operations administrator"
},
"companyTypes": null,
"industries": null,
"fileTypes": null
}
我正在尝试过滤,但没有到达目的地
const myFilter = (resp, num) => {
const values = resp.filter(det => !!det.roles.find(l => l === num));
return values.map(res => {
res.roles = res.roles.filter(l => l === num);
return res;
});
};
答案 0 :(得分:2)
只需找到给定值的索引(“ HR Admin”)并获取该索引的键即可:
const obj = {
"genders": null,
"races": null,
"titles": null,
"maritalStatus": null,
"nationality": null,
"identityTypes": null,
"roles": {
"1": "System Admin",
"2": "Internal Account Manager",
"3": "CAT Manager",
"4": "HR Admin",
"5": "HR Manager",
"6": "HR Recruiter",
"7": "Candidate",
"8": "Operations administrator"
},
"companyTypes": null,
"industries": null,
"fileTypes": null
};
const search = 'HR Admin';
const index = Object.values(obj.roles).indexOf(search);
const result = Object.keys(obj.roles)[index];
console.log(result);