arrays - Search through a JavaScript object and its nested properties looking for something in underscore -
i looking use .where or .find through array of objects like:
looking user inputs might match.
so imaging, have expanded object have array of them. can see here, there relationship between object (user) , profile (the expanded node). if enter in (into search box) "ca", should matching elements because see here: user.profile.data.country === 'ca'
evaluates true.
now if enter in "kyle", again should object because middle_name kyle.
the question is, how use where
or find
search array of objects, going deep nesting goes search value matches?
an example of how deep nesting can go:
- user - profile - contact_info - id_verification - investments (array) - offering - company
if type in "shoppers" , shoppers company return object. ideas?
you can use recursion find property given value; added path attribute indicate nested object found
var data = { user: { profile: {}, contact_info: {}, id_verification: { name: 'any' }, investments: [{ offering: "an offer", company: "acme" }, { offering: "an offer", company: "shopping" }] } } function search(obj, tomatch, path) { path = path ? path : ''; if ((!_.isobject(obj) && !_.isarray(obj)) || _.isempty(obj)) return false; var = _.indexof(_.values(obj), tomatch) if (i > -1) { var f = {} f[_.keys(obj)[i]] = _.values(obj)[i]; f.path = path; return f; } else { path = path + '|any' (var v in obj) { var = path.split('|') a.pop(); a.push(v); path = a.join('|'); var found = search(obj[v], tomatch, path); if (found) { return found; } } } } search(data, 'shopping')
Comments
Post a Comment