Skip to content

Instantly share code, notes, and snippets.

@junwatu
Last active August 29, 2015 14:06
Show Gist options
  • Save junwatu/b37ffc07987e085c69ec to your computer and use it in GitHub Desktop.
Save junwatu/b37ffc07987e085c69ec to your computer and use it in GitHub Desktop.
Filter values on nested object based on key name -- http://jsbin.com/cunalopopule/15
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Filter values on nested object based on key name" />
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-source-javascript" type="text/javascript">
// Data samples
var data = {
tags: [ 'dolor' ],
children: [
{ foo: 'bar', tags: ['morphin', "ipsum"] },
{ baz: 'buzzle', tags: null, tags:['aten', 'solis'] },
{ morbid: 'angel', tags: [Object]}
]
}
var data2 = {
"name": "First object",
"tags": ["diam", "ipsum", "ipsum", "consectetur"]
};
var data3 = {
"name": "Second object",
"tags": ["yolo", "ipsum", "diam", "amet", "lectus"]
}
/**
* Filter out values with 'tags' key ith recursive function.
*/
var tags_array = [];
function r(obj) {
if (obj)
for (var key in obj) {
if (typeof obj[key] == "object"){
r(obj[key]);
}
else if (typeof obj[key] != "function"){
if(!obj.hasOwnProperty('tags')){
tags_array.push(obj[key]);
}
}
}
}
// try it with data2 or data3
r(data)
console.log(tags_array);
</script>
</body>
</html>
// Data samples
var data = {
tags: [ 'dolor' ],
children: [
{ foo: 'bar', tags: ['morphin', "ipsum"] },
{ baz: 'buzzle', tags: null, tags:['aten', 'solis'] },
{ morbid: 'angel', tags: [Object]}
]
}
var data2 = {
"name": "First object",
"tags": ["diam", "ipsum", "ipsum", "consectetur"]
};
var data3 = {
"name": "Second object",
"tags": ["yolo", "ipsum", "diam", "amet", "lectus"]
}
/**
* Filter out values with 'tags' key ith recursive function.
*/
var tags_array = [];
function r(obj) {
if (obj)
for (var key in obj) {
if (typeof obj[key] == "object"){
r(obj[key]);
}
else if (typeof obj[key] != "function"){
if(!obj.hasOwnProperty('tags')){
tags_array.push(obj[key]);
}
}
}
}
// try it with data2 or data3
r(data)
console.log(tags_array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment