Last active
September 7, 2022 02:35
-
-
Save LRENZ/5b3f96d4a0e31e200ca5100901b3a763 to your computer and use it in GitHub Desktop.
find multi dimension dataLayer value
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 nodeExplorer = function (node, key, val, count) { | |
var k, | |
r, | |
j, | |
checkCount = count || 0; | |
if (!!node && node[key] !== undefined) { | |
if(!!val && node[key] === val){ | |
return node; | |
} | |
if(!val){ | |
return node; | |
} | |
} | |
if (node instanceof Array && checkCount < 5) { | |
for (k = node.length - 1; k >= 0; k -= 1) { | |
r = nodeExplorer(node[k], key, val, checkCount+1); | |
if (r !== undefined) { | |
return r; | |
} | |
} | |
} else if (typeof node === "object" && checkCount < 5) { | |
for (j in node) { | |
if (node.hasOwnProperty(j)) { | |
r = nodeExplorer(node[j], key, val, checkCount+1); | |
if (r !== undefined) { | |
return r; | |
} | |
} | |
} | |
} | |
}; | |
var getDataLayerValue = function(key) { | |
var res = nodeExplorer(window.dataLayer, key); | |
return res ? res[key] : undefined; | |
}; | |
var getDataLayerObject = function(key, val){ | |
var res = nodeExplorer(window.dataLayer, key, val); | |
return !!res ? res : false; | |
}; | |
var getDataLayerListById = function(key) { | |
var _nodeExplorer = function(node, key, ret, count) { | |
var k, | |
j, | |
checkCount = count || 0; | |
if (!!node && node[key] !== undefined) { | |
if (node[key]) { | |
ret.push(node); | |
} | |
} | |
if (node instanceof Array && checkCount < 5) { | |
for (k = node.length - 1; k >= 0; k -= 1) { | |
r = _nodeExplorer(node[k], key, ret, checkCount+1); | |
} | |
} else if (typeof node === "object" && checkCount < 5) { | |
for (j in node) { | |
if (node.hasOwnProperty(j)) { | |
r = _nodeExplorer(node[j], key, ret, checkCount+1); | |
} | |
} | |
} | |
return ret; | |
}; | |
return _nodeExplorer(this.dataLayer, key, []); | |
}; | |
function getDatalayerList(key){ | |
var dl = getDataLayerListById(key) | |
var ls = []; | |
var list = dl.map( function(t){ | |
//debugger | |
if(!!t[key]){ | |
ls.push(t[key]) | |
} | |
}) | |
return ls | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment