2

I have an object like below:

myObj = {
  "name":"John",
  "age":30,
  "cars":[ "Ford", "BMW", "Fiat" ]
}

How can I know the property name "cars" when I input "BMW"? I need a function which needs to return property name "cars" when I pass the argument "BMW" in the function.

2
  • Please show us function. Commented Jan 30, 2017 at 8:02
  • Have you tried looping through the object values and comparing them to the function parameter? Commented Jan 30, 2017 at 8:03

3 Answers 3

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');

here is demo https://plnkr.co/edit/wVFGcAKuml4rWuIaMx2K?p=preview

Sign up to request clarification or add additional context in comments.

Comments

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'

Hope this helps!

Comments

0

You cna do something like this

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'))

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.