Validate javascript object keys against an array - Stack Overflow

admin2025-04-08  0

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 something like:

{ name: 'Luke Skywalker', gender: 'Male', hasTheForce: true } // => true
{ name: 'James Brown', gender: 'Male', hasTheFunk: true } // => false

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 something like:

{ name: 'Luke Skywalker', gender: 'Male', hasTheForce: true } // => true
{ name: 'James Brown', gender: 'Male', hasTheFunk: true } // => false
Share Improve this question asked May 29, 2017 at 10:25 malimichaelmalimichael 2471 gold badge6 silver badges18 bronze badges 2
  • @synthet1c please explain why? hasTheFunk is not one of the validKeyNames – malimichael Commented May 29, 2017 at 10:29
  • misread the objects keys – synthet1c Commented May 29, 2017 at 10:34
Add a ment  | 

4 Answers 4

Reset to default 6

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))

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.

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

I think you can validate using something like this:

    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).sort().toString() === arr.sort().toString()
}

console.log(check(a, validKeyNames))
console.log(check(b, validKeyNames))

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744124080a232381.html

最新回复(0)