Emphram Stavanger
Emphram Stavanger

Reputation: 4214

Check if object contains all keys in array

How can I most succinctly check if an object contains ALL of the keys specified in an array?

For example:

var arr = ["foo", "bar"];

var obj = {
  foo: 1,
  bar: "hello"
};

magic_function(arr, obj); // return true, all keys from array exist


var obj2 = {
  foo: 12,
  bar: "hi",
  test: "hey"
};

magic_function(arr, obj2); // return true, all keys from array exist,
                           // keys not specified in array don't matter


var obj3 = {
  foo: 5
};

magic_function(arr, obj3); // return false, "bar" is missing

Upvotes: 12

Views: 17445

Answers (3)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

We can check in the following way

const arr = ["foo", "bar"];

const obj = {
  foo: 1,
  bar: "hello"
};

const hasAllKeys = label => Object.prototype.hasOwnProperty.call(obj, label);

console.log(arr.every(item => hasAllKeys(item)));

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72857

This should do it:

const arr = ["foo", "bar"];

const obj = {
  foo: 1,
  bar: "hello"
};

const hasAllKeys = arr.every(item => obj.hasOwnProperty(item));

console.log(hasAllKeys);

Array.prototype.every() returns true if the passed function returns true for every item in the array.
Object.prototype.hasOwnProperty() is pretty self-explanatory.

Upvotes: 32

Nina Scholz
Nina Scholz

Reputation: 386578

You could iterate the array and check for the key with in operator

The in operator returns true if the specified property is in the specified object.

The difference between in operator and Object#hasOwnProperty is, in checks all properties, even the ones from the prototype, like toString (as in the example) and Object#hasOwnProperty checks only own properties, without the properties from the prototypes.

function checkKeys(keys, object) {
    return keys.every(function (key) {
        return key in object;
    });
}

function checkOwnKeys(keys, object) {
    return keys.every(function (key) {
        return object.hasOwnProperty(key);
    });
}

var arr = ["foo", "bar", "toString"],
    obj = { foo: 1, bar: "hello" };

console.log(checkKeys(arr, obj));                // true
console.log(checkOwnKeys(arr, obj));             // false
console.log(checkOwnKeys(["foo", "bar"], obj));  // true

Upvotes: 9

Related Questions