Validate Javascript Object Keys Against An Array
Given the following array const validKeyNames = ['name', 'gender', 'hasTheForce'] Is it possible to check an objects key is one of an arrays elements. I want to be able to do some
Solution 1:
You can use every()
on Object.Keys()
and check if key exists in array using includes()
const validKeyNames = ['name', 'gender', 'hasTheForce']
var a = { name: 'Luke Skywalker', gender: 'Male', hasTheForce: true }
var b = { name: 'James Brown', gender: 'Male', hasTheFunk: true }
function check(obj, arr) {
return Object.keys(obj).every(e => arr.includes(e));
}
console.log(check(a, validKeyNames))
console.log(check(b, validKeyNames))
Solution 2:
I will give you an idea on how to achieve this.
1.Sort the array of valid keys initially using .sort()
.
2.For each key in the object(using for in
loop) check whether it is present in the array of valids until key <= array[iterator]
. Whenever key > array[iterator]
you can safely confirm that key is not present in the array.
Solution 3:
You could use Object.hasOwnProperty
and bind the object for checking.
function check(object) {
return validKeyNames.every({}.hasOwnProperty.bind(object));
}
const validKeyNames = ['name', 'gender', 'hasTheForce']
console.log(check({ name: 'Luke Skywalker', gender: 'Male', hasTheForce: true })); // true
console.log(check({ name: 'James Brown', gender: 'Male', hasTheFunk: true })); // false
Post a Comment for "Validate Javascript Object Keys Against An Array"