Optimus Prime
Optimus Prime

Reputation: 308

How can get the property name of an object array value?

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.

Upvotes: 2

Views: 73

Answers (3)

brk
brk

Reputation: 50346

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

Upvotes: 0

Santanu Biswas
Santanu Biswas

Reputation: 4787

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!

Upvotes: 0

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

Upvotes: 2

Related Questions