Arshad Rehmani
Arshad Rehmani

Reputation: 2185

Check if javascript object contains some of gives keys

I have an object of around 10 Arrays. And I want to check if objects contains one of the 2 arrays. ( I know the names of arrays that server returns)

data.serverObjects = {
  cityNames : [],
  cityCodes: [],
  cityMapData: []
}

I'm trying to achieve below results:

data.serverObject.hasOneOfKey('key1', 'key2')  //should return false
data.serverObject.hasOneOfKey('cityNames', 'key2')  //should return true

I wanted to do it by using _.findKey , but i use version 1.6 of underscore which doesn't support this function.

Please suggest some solution.

Upvotes: 0

Views: 74

Answers (4)

Danny
Danny

Reputation: 664

Here's a functional solution:

Object.prototype.hasOneOfKey = function(keys){
    return Object.keys(this).filter(function(d){
        return keys.indexOf(d) >= 0;
    }).length > 0;
}

Example:

var person = {
    name: "Bart",
    surname: "Simpson"
};

person.hasOneOfKey(["name","age"]); // true
person.hasOneOfKey(["age"]);        // false

Upvotes: 0

Arshad Rehmani
Arshad Rehmani

Reputation: 2185

Since I'm fan on underscore, I came up with below solution. Please suggest if this looks good.

Given object is,

var serverObjects = {
  cityNames: [],
  cityCodes: [],
  cityMapData: []
}

Solution:

var serverObject = _.keys(data.serverObject);
var hasOneOfKey = _.any(serverObject, function (property) {
    return (property.indexOf('cityNames') !== -1 || property.indexOf('key') !== -1);
});

Upvotes: 0

Pugazh
Pugazh

Reputation: 9561

Here is a solution.

P.S: This works with only 2 values in the function hasOneOfKey

var serverObjects = {
  cityNames: [],
  cityCodes: [],
  cityMapData: []
}

Object.prototype.hasOneOfKey = function(a, b) {
  return (a in this || b in this);
}

console.log(serverObjects.hasOneOfKey('key1', 'key2'));

console.log(serverObjects.hasOneOfKey('key1', 'cityNames'));

Upvotes: 0

pwolaq
pwolaq

Reputation: 6381

Just iterate over keys and check with hasOwnProperty:

Object.prototype.hasOneOfKey = function(){
    for(var i=0;i<arguments.length;i++){
        if(this.hasOwnProperty(arguments[i])){
            return true;
        }
    }

    return false;
};

Upvotes: 2

Related Questions