使用map在json对象id上搜索数据的最佳实践

时间:2017-08-29 11:31:51

标签: javascript angularjs json typescript

让我如何在javascript中找到一个json 示例Json:

   {
"Employees" : [
{
"userId":"rirani",
"jobTitleName":"Developer",

"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani@gmail.com"
},
{
"userId":"nirani",
"jobTitleName":"Developer",    
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"neilrirani@gmail.com"
}
]
]
}

上面的json我希望根据employeeCode,emailAddress和PhoneNumber找到特定的userId。目前我正在做如下

for(var i=0; i<json.length;i++){
       if((employeeCode==code)&&(emailAddress ==email)&&(PhoneNumber==phone)){
                     //here i am getting userId
        }   
    }

我想知道这是否正确。如果它是小json加载它确定。但如果是我需要做的大规模数据。

2 个答案:

答案 0 :(得分:1)

您只需使用map数组中的Employee函数:

var data =    {
"Employees" : [
{
"userId":"rirani",
"jobTitleName":"Developer",

"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani@gmail.com"
},
{
"userId":"nirani",
"jobTitleName":"Developer",    
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"neilrirani@gmail.com"
}
]

};

var code ='E2' , email ='neilrirani@gmail.com' , phone = '408-1111111', userId;
data.Employees.map(x=>{
   if(x.employeeCode == code && x.phoneNumber == phone && x.emailAddress== email){
     userId = x.userId;
  }
});

console.log(userId);

答案 1 :(得分:0)

您可以使用find方法接受应用于数组中每个项目的callback提供的函数。

  

find()方法返回数组中第一个元素的值   满足提供的测试功能。否则未定义   返回。

let emailAddress="neilrirani@gmail.com";
let phone="408-1111111";
let code="E2";
let Employees = [
{
"userId":"rirani",
"jobTitleName":"Developer",
"preferredFullName":"Romin Irani",
"employeeCode":"E1",
"region":"CA",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani@gmail.com"
},
{
"userId":"nirani",
"jobTitleName":"Developer",    
"preferredFullName":"Neil Irani",
"employeeCode":"E2",
"region":"CA",
"phoneNumber":"408-1111111",
"emailAddress":"neilrirani@gmail.com"
}
];
let employee=Employees.find(function(employee){
    return employee.emailAddress==emailAddress && employee.phoneNumber==phone && employee.employeeCode==code;
});
console.log(employee.userId);