如何按键值查找嵌套数组?

时间:2014-06-04 16:41:52

标签: javascript jquery arrays

根据用户点击的作业,我想要用来将数据抽取到把手模板中的JS数组作业。

var data = { jobs: [
   {jobName:"ACME", jobRole: "Vice President", jobDesc: "..."},
   {jobName:"Square Co", jobRole: "Director", jobDesc: "..."},
   {jobName:"Compu Mega Net", jobRole: "Manager", jobDesc: "..."}
]};

我有一组元素,每个元素都有一个与要显示的jobName匹配的数据属性。

<a href="#" class="job" data-jobName="ACME">
<a href="#" class="job" data-jobName="Square Co">
<a href="#" class="job" data-jobName="Compu Mega Net">

问题是:如何查找数组中与用户选择的jobName匹配的相应对象?

我尝试过使用$.inArray("ACME", data);$.inArray("ACME", data.jobs);,但总是回来-1(未找到)。

3 个答案:

答案 0 :(得分:2)

jQuery有$.grep可以进行搜索。例如,如果您知道目标对象将始终存在,则可以执行以下操作:

$('a').click(function(){
    var search = $(this).data('jobname');
    var result = $.grep(data.jobs, function(obj){ return obj.jobName == search; })[0];
    console.log(result); // the target object
});

如果你不确定该对象是否存在,那么你需要检查返回值,而不是直接访问第一个元素:

$('a').click(function(){
    var search = $(this).data('jobname');
    var resultArray = $.grep(data.jobs, function(obj){ return obj.jobName == search; });

    if(resultArray.length > 0){
        console.log( resultArray[0] ); // the target object
    } 
});

答案 1 :(得分:1)

这将产生一个数组:

var matchingJobs = data.jobs.filter(function(job){ return job.jobName == "ACME" });

您可以像这样从中拉出最后一个匹配的作业:

var firstMatch = matchingJobs.pop();

答案 2 :(得分:0)

function ObjectSelected(jobName_selected) { 
    var  appropriate_object = null; 

    var data = { jobs: [
       {jobName:"ACME", jobRole: "Vice President", jobDesc: "..."},
       {jobName:"Square Co", jobRole: "Director", jobDesc: "..."},
       {jobName:"Compu Mega Net", jobRole: "Manager", jobDesc: "..."}
    ]};

    for(var i = 0;i < data.length;i++)
        if(data[i].jobName = jobName_selected)
            appropriate_object = data[i];
}