2015-09-10 68 views
0

我有一个JSON对象构造为这样:过滤JSON具有独特的键/值

var theSchools = { 
    Bradley University: "bru", 
    Knox College: "knox", 
    Southern Illinois University Edwardsville: "siue",… 
} 

我所试图实现的是检索的关键,在这种情况下,学校名称的方式,通过提供价值,学校的代码。“

它不会出现,我就能有这样的正确调整,即

var theSchools = [ 
    { 
    schoolName:"Bradley University", 
    schoolCode: "bru"  
    } 
    { 
    schoolName: "Knox College", 
    schoolCode: "knox" 
    } 
] 

所以我那种坚持我得到了什么。

我知道下面的代码是不正确的,但它本质上是我想达到的目标:

if(getParameterByName("schoolId").length>0){ 
    var schoolid = getParameterByName("schoolId"); 
    var schoolName= theSchools.schoolid;   

    jQuery("h1").after("<h2>Welcome to <strong>"+schoolName+"</strong></h2>") 
} 

回答

2

可以使用for...in loop遍历对象中的每个属性,如果返回值的属性名称比赛:

var theSchools = { 
 
    "Bradley University": "bru", 
 
    "Knox College": "knox", 
 
    "Southern Illinois University Edwardsville": "siue" 
 
}; 
 

 
function findSchool(code) { 
 
    for (var s in theSchools) { 
 
     if (theSchools[s] === code) 
 
      return s; 
 
    } 
 
    return null; 
 
} 
 

 
document.getElementById('school').innerText = findSchool('knox');
<div id="school"></div>

0

的问题是,如果你真的需要这种方式(见nswer @James),这里是你要求的:

var theSchools = { 
    "Bradley University": "bru", 
    "Knox College": "knox", 
    "Southern Illinois University Edwardsville": "siue" 
}, schoolMap = {}; 

for (var schoolName in theSchools) { 
    var code = theSchools[ schoolName ]; 
    schoolMap[ code ] = schoolName; 
} 

document.body.innerHTML = schoolMap["bru"]; // Bradley University 
0

你不必使用for循环来检查属性是否存在。使用hasOwnProperty方法。

if (theSchools.hasOwnProperty("Knox College")) { 
    //do stuff 
} 

工作例如:https://jsfiddle.net/7q9czdpc/

+0

你需要知道属性的名称才能做到这一点。 OP知道财产(学校代码)的价值并需要找到其名称。 –

+0

我的不好。 以下是您所需要的: http://jsfiddle.net/maT7ew/y4jhyhh3/1/ –