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
Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
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.
You could iterate the array and check for the key with in
operator
The
in
operator returnstrue
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With