Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple keys exists in json object

I am trying to validate the request object to check if specific keys exist in the object or not. I've tried lodash's has() function, but it seems that _.has() checks nested JSON. Javascript's .hasOwnProperty() takes one key at a time. Is it possible to check an array of keys within a plain JSON object?

The object I am trying to check is

 {
    "name": "[email protected]",
    "oldPassword": "1234",
    "newPassword": "12345"
}
like image 618
Shashank Avatar asked Feb 26 '19 09:02

Shashank


2 Answers

Simply use Object.keys and every

const neededKeys = ['oldPassword', 'name', 'newPassword'];

const obj = {
    "name": "[email protected]",
    "oldPassword": "1234",
    "newPassword": "12345"
}

console.log(neededKeys.every(key => Object.keys(obj).includes(key)));
like image 51
baao Avatar answered Sep 24 '22 07:09

baao


You can use .includes method of an array and Object.keys will give you an array of all the keys. You can compare this with an array of keys from which you want to check using a loop

var a = {
  "name": "[email protected]",
  "oldPassword": "1234",
  "newPassword": "12345"
};
var key = ["name", "oldPassword", "newPassword"];
Object.keys(a).forEach(e => key.includes(e) ? console.log(e + " found") : console.log(e + " not found"))
like image 41
ellipsis Avatar answered Sep 24 '22 07:09

ellipsis