我有一个如下的对象:
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
我如何知道物业名称"汽车"当我输入"宝马"?我需要一个需要返回属性名称的功能" cars"当我通过论证"宝马"在功能中。
答案 0 :(得分:2)
function getKeyByitem(myObj, value)
for (var key in myObj) {
if (myObj.hasOwnProperty(key) && Array.isArray(myObj[key])) {
if(myObj[key].indexOf(value) != -1){
return key;
}
}
}
}
var key = getKeyByitem(myObj, 'BMW');
这里是demo https://plnkr.co/edit/wVFGcAKuml4rWuIaMx2K?p=preview
答案 1 :(得分:0)
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
var findKey = function (str) {
var keys = Object.getOwnPropertyNames(myObj);
var key = null;
var match = keys.some(function (k) {
key = k;
var val = myObj[key];
if (Array.isArray(val)) {
return val.indexOf(str) >= 0;
} else {
return val.toString() === str;
}
return false;
});
if (match) return key;
}
console.log(findKey('BMW')); // 'cars'
console.log(findKey('John')); // 'name'
console.log(findKey('30')); // 'age'
希望这有帮助!
答案 2 :(得分:0)
你可以做这样的事情
var myObj = {
"name": "John",
"age": 30,
"cars": ["Ford", "BMW", "Fiat"]
}
var getKey=function(elem) {
var toReturn = '';
for (var k in myObj) { // loop through the object
if(Array.isArray(myObj[k])){
if(myObj[k].indexOf(elem) !== -1){
toReturn = k;
}
}
else{
if(myObj[k] === elem){
toReturn = k
}
}
}
return toReturn;
}
console.log(getKey('BMW'))