Last active
June 22, 2016 19:51
-
-
Save daniellizik-sc/d6e018b65867f3f6c501f22de6e22e2f to your computer and use it in GitHub Desktop.
deepsearch find first
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var deepsearch_find_first = function(needle, haystack, parent) { | |
var iterable; | |
if (Object.prototype.toString.call(haystack) === '[object Array]') { | |
iterable = haystack; | |
} else if (Object.prototype.toString.call(haystack) === '[object Object]') { | |
iterable = Object.keys(haystack); | |
} else { | |
return; | |
} | |
if ((haystack || {}).hasOwnProperty(needle)) { | |
return haystack[needle]; | |
} | |
for (var i = 0; i < iterable.length; i++) { | |
var key = haystack.hasOwnProperty(iterable[i]) ? haystack[iterable[i]] : iterable[i]; | |
var found = deepsearch_find_first(needle, key, haystack); | |
if (found) { | |
return found; | |
} | |
} | |
} | |
var products = deepsearch_find_first('products', window.dataLayer); | |
console.log(Array.isArray(products), 'deepsearch should return array'); | |
console.log(products.length > 0, 'deepsearch result length should be > 0'); | |
console.log(products[0].hasOwnProperty('name'), 'products item should have name property'); | |
console.log(products[0].hasOwnProperty('brand'), 'products item should have brand property'); | |
console.log(products[0].hasOwnProperty('category'), 'products item should have category property'); | |
console.log(products[0].hasOwnProperty('id'), 'products item should have id property'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment