1

What is the best way to do? I am interested in lodash methods as well if there is any better approach

var myObj = {
  name: 'John',
  age: 20,
  sex: male
}

I like to see whether myObj have 'name' and 'age' keys

My Approach - it works fine

var myObj = {
  name: 'John',
  age: 20,
  sex: 'male'
}
var value;

function result() {
  if (myObj.hasOwnProperty('name') && myObj.hasOwnProperty('age')) {
    value = true;
  } else {
    value = false;
  }
}
result();
console.log(value);

I can also use ('key' in myObj)

But actually I has an object which is quiet big and need to check if they have particular keys. Looking for any better approach

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Mahesh
  • 221
  • 1
  • 3
  • 14
  • 1
    Tons of way to do it.... but if it is just a few keys, what you are doing is fine. If it is a lot of keys, object with a loop is better. – epascarello Sep 19 '18 at 18:50
  • possible duplicate - https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key – Naga Sai A Sep 19 '18 at 18:53
  • Please edit your question to be more descriptive about what you mean by "better approach". Is there something specific about what you're doing that makes you want another way? – Ruzihm Sep 19 '18 at 18:54
  • @Naga Sai it is but not as straigh forward as this – Mahesh Sep 19 '18 at 19:00

6 Answers6

2

Put your required keys into an array:

let requiredKeys = ["name", "age"];

And then use the Array.every method and Object.keys:

let objectKeys = Object.keys(myObj);
let hasRequiredKeys = requiredKeys.every(k => objectKeys.includes(k));
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Create an array of keys. Iterate the array with Array.every(), and check if each key is in the object using Object.hasOwnProperty():

const myObj = {
  name: 'John',
  age: 20,
  sex: 'male'
};

const hasKeys = (obj, keys) => keys.every(key => obj.hasOwnProperty(key));
  
console.log(hasKeys(myObj, ['name', 'age']));

console.log(hasKeys(myObj, ['name', 'title']));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

Using lodash, with the has method

var _ = require('lodash');
var myObj = {
   name: 'John',
   age: 20,
   sex: male
}

var has_keys = _.has(myObj, ['name', 'age', 'sex']);
// has_keys => true
selby
  • 11
  • 1
0
function validateObj (myObj) {
   var nameFound = false;
   var ageFound = false;
   for (x in myObj) {
       if (x === "name") nameFound = true;
       if (x === "age")  ageFound = true;
       if (ageFound && nameFound) return true;
   }
   return (ageFound && nameFound)
}
Matt Kuhns
  • 1,328
  • 1
  • 13
  • 26
0

There are some subtleties to this question that may or may not be important.

Objects in Javascript have prototypes that can inherit properties from other objects. It's not clear whether myObj would be valid if one of the required properties is found on the prototype.

Here's an example:

const parent = {
    name: 'John',
    age: 20,
    sex: 'male'
  }
 
const requiredKeys = ['name', 'age']

let valid = requiredKeys.every(key => parent.hasOwnProperty(key))

// valid becuase parent has name and age
console.log("Parent valid:", valid)

// but what about child that inherits from parent:

let child = Object.create(parent)

valid = requiredKeys.every(key => child.hasOwnProperty(key))

// not valid becuase child doesn't directly has name and age
console.log("Child Valid:", valid)

// yet those properties seem to exist because you can get them through parent's prototype:
console.log("Child name and age:", child.name, child.age)

// you can test up the protoytpe chain with …in:

valid = requiredKeys.every(key => key in child)

// now valid becuase child has name and age somewhere in the prototype chain 
console.log("Child Valid (with prototype):", valid)

So the question would be: which is most appropriate for your use case.

Mark
  • 90,562
  • 7
  • 108
  • 148
0

I like using lodash get for deep objects. Reason is to handle issue when any deep property is undefined or not present. Instead of errors on console and stuff use -

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c'); // => 3

_.get(object, ['a', '0', 'b', 'c']); // => 3

_.get(object, 'a.b.c', 'default'); // => 'default'

From - https://lodash.com/docs/4.17.10#get