Skip to content

Instantly share code, notes, and snippets.

@stewartmcgown
Created January 15, 2019 12:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stewartmcgown/d5e165c2b6bd1c24d4bb922247edc046 to your computer and use it in GitHub Desktop.
Save stewartmcgown/d5e165c2b6bd1c24d4bb922247edc046 to your computer and use it in GitHub Desktop.
Partial Match properties of Object Array (ES6)
/**
* Are all the values on p present on o
* @param {Object} o object to search
* @param {Object} p object of search values
* @param {Boolean} [c] are loose equality matches ok?
* @return {Boolean} whether there are partial matches
*/
const partialMatch = (o, p, c) =>
Object.keys(p).every(k =>
p[k] && o[k]
? p[k] instanceof Object
? partialMatch(o[k], p[k], c)
: c
? o[k].toLowerCase().includes(p[k].toLowerCase())
: p[k] === o[k]
: false
)
/**
*
* @param {Array.<Object>} o An array of objects
* @param {Object} p the properties to match
* @param {Boolean} c if a partial match is enough
* @return {Array.<Object>} matching objects
*/
const partialSearch = (o, p, c) => {
o instanceof Array ? o : (o = Object.values(o))
return o.filter(a => partialMatch(a, p, c))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment