1

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
2
  • @synthet1c please explain why? hasTheFunk is not one of the validKeyNames Commented May 29, 2017 at 10:29
  • misread the objects keys Commented May 29, 2017 at 10:34

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

3 Comments

Yes but... this fails when you have a target object like { name: 'Luke Skywalker', gender: 'Male', hasTheForce: true , batter: 'boo'}.. Still more valid than the accepted answer...
@Redu, what fails in the above case?
OP says "check an objects key is one of an arrays elements" ... so batter as an object key (property) is not not one of the array elements.. yet your code returns true.check an objects key is one of an arrays elements
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.