如果传入的值是 json 对象,如何检索键?
How to retrieve key if passed in value is a json object?
var json={"america":"1234","india:"5678","britain":"789"}
这是一个示例 json 对象(实际 json 对象中有数千个键值对)。如果我传递值 json["1234"],如何从此对象检索密钥?预期的结果是我应该能够检索密钥 "america".
var json = {"america":"1234","india":"5678","britain":"789"};
function getValueByKey(obj, val) {
// Looping on object keys
return Object.keys(obj).filter(function (key) {
return obj[key] === val
})[0];
}
// For testing
console.log(getValueByKey(json, "1234")); // america
console.log(getValueByKey(json, "5678")); // india
var json={"america":"1234","india:"5678","britain":"789"}
这是一个示例 json 对象(实际 json 对象中有数千个键值对)。如果我传递值 json["1234"],如何从此对象检索密钥?预期的结果是我应该能够检索密钥 "america".
var json = {"america":"1234","india":"5678","britain":"789"};
function getValueByKey(obj, val) {
// Looping on object keys
return Object.keys(obj).filter(function (key) {
return obj[key] === val
})[0];
}
// For testing
console.log(getValueByKey(json, "1234")); // america
console.log(getValueByKey(json, "5678")); // india