简体   繁体   中英

what is the easiest way to test if a value exists in an object using lodash or angularjs

This works if obj is a collection but if I am just trying to test if a value exists in a single object it is not working. What is the most efficient way using lodash or angularjs to test if a serach term exists within an object? Thanks!!

 var obj = { id: 4, name: 'test', value: 'car', description: 'I like soup' } var searchTerm= 'soup'; var testObject = function(){ var status = true; status = _.some(obj, searchTerm); console.dir(status); } testObject(); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script> <script src="lodash.js"></script> 

You can use lodash's _.values and _.some with a predicate to make this work.

 var obj = { id: 45, name: 'test', value: 'car', description: 'I like soup' } var testObject = function(searchTerm){ console.log(_.some(_.values(obj), function (s) { return _.isString(s) ? s.indexOf(searchTerm) !== -1 : '' + s === searchTerm; })); } testObject('soup'); testObject('4'); testObject('45'); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script> 

A simple but not optimal way, looks everywhere in the object hierarchy.

function hasKeyValue(object, keyValue)
{
return JSON.stringify(object).indexOf(':"'+keyValue+'"') !== -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM