Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if key exists in object with lodash

Tags:

I need help with lodash cause i dont understand functional programming and lodash is very helpfull with object/arrays operations.

I need to search objects inside object and return true if key exists. I've setup a jsfiddle. Apreciate your help.

    var dependsOn={       "Cadastro": {         "RHID": "RHID"       },       "Agregados":{         "CD_DOC":"CD_DOC"       }       "Documentos":{         "RHID":"CD_DOC"       }     }     var field='RHID'  alert(_.contains(_.keys(dependsOn), field)) 

https://jsfiddle.net/88gwp87k/

like image 851
Leonel Matias Domingos Avatar asked Feb 26 '16 12:02

Leonel Matias Domingos


People also ask

How do I check if an object has a key in Lodash?

Lodash _.has() Method The _.has() method is used to check whether the path is a direct property of object or not. It returns true if path exists, else it returns false.

How do you know if a key is present in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

Why you should not use Lodash?

Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])


2 Answers

Try this. it's simple

_.has(dependsOn, field) 

it returns true if the RHID key exist in dependsOn. in above case it returns false

like image 88
Fawad Mukhtar Avatar answered Sep 19 '22 10:09

Fawad Mukhtar


try this

var dependsOn={   "Cadastro": {     "RHID": "RHID"   },   "Agregados":{     "CD_DOC":"CD_DOC"   },   "Documentos":{     "RHID":"CD_DOC"   } } var field='RHID'  alert(_.some(dependsOn, function(o) { return _.has(o, field); })); 

Updated your fiddle: https://jsfiddle.net/88gwp87k/1/

like image 25
Narendra CM Avatar answered Sep 21 '22 10:09

Narendra CM