2015-06-14 56 views
0

如何根據值獲取密鑰。我的 傳遞的值是 'A',我應該拿到鑰匙 '屬性'如何根據json中的值使用jquery獲取密鑰

{ 
    "Employees": { 
     "Attributes": [ 
      "A", 
      "V", 
      "C", 
      "ZZ", 
      "D", 
      "E", 
      "F", 
      "G", 
      "H", 
      "I", 
      "J" 
     ], 
     "Both": [ 
      "XXX", 
      "YYY" 
     ] 
    } 
} 
+1

你有沒有考慮過使用loda sh(或下劃線)?如果這是您的代碼中經常查找的內容,則可能需要創建並反轉數據結構:http://devdocs.io/lodash/index#invert – Risadinha

+0

您目前編寫了哪些代碼以嘗試獲取此代碼? –

回答

0

嘗試利用Object.keysArray.prototype.filter

var data = { 
 
    "Employees": { 
 
     "Attributes": [ 
 
      "A", 
 
      "V", 
 
      "C", 
 
      "ZZ", 
 
      "D", 
 
      "E", 
 
      "F", 
 
      "G", 
 
      "H", 
 
      "I", 
 
      "J" 
 
     ], 
 
     "Both": [ 
 
      "XXX", 
 
      "YYY" 
 
     ] 
 
    } 
 
}; 
 

 
var q = "A"; 
 

 
var res = Object.keys(data.Employees).filter(function(val, key) { 
 
    return data.Employees[val].indexOf(q) !== -1 
 
})[0]; 
 

 
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

1

嘗試這樣

var data={ 
    "Employees": { 
     "Attributes": [ 
      "A", 
      "V", 
      "C", 
      "ZZ", 
      "D", 
      "E", 
      "F", 
      "G", 
      "H", 
      "I", 
      "J" 
     ], 
     "Both": [ 
      "XXX", 
      "YYY" 
     ] 
    } 
}; 
var searchValue="A"; 
for(var i in data.Employees){ 
    if(data.Employees[i].indexOf(searchValue)>-1){ 
     console.log(i); 
     break; 
    } 
}