Skip to content

Instantly share code, notes, and snippets.

@klesouza
Created September 5, 2017 20:38
Show Gist options
  • Save klesouza/8cfc4265b4536359ce90efd5526aa398 to your computer and use it in GitHub Desktop.
Save klesouza/8cfc4265b4536359ce90efd5526aa398 to your computer and use it in GitHub Desktop.
Javascript to filter json properties
<html>
<body>
<textarea name="" id="json" cols="30" rows="10"></textarea>
<input id="filter" />
<textarea name="" id="result" cols="30" rows="10"></textarea>
<button onclick="send()">Filter</button>
</body>
<script type="text/javascript">
var a = {
fare: [
{
legs: [{
prop1: "asd",
prop2: "234"
}]
}
]
};
function filter(original, dest, f){
var props = f.split('.');
var x = props[0];
var obj = {};
if(f === "")
return;
dest[x] = {};
if(typeof(original[x]) == typeof([])){
obj = []
for(var i in original[x]){
var it = {};
filter(original[x][i], it, f.replace(x+'.', ""))
obj.push(it);
}
dest[x] = obj;
}
else if(typeof(original[x]) == 'object')
filter(original[x], dest[x], f.replace(x+'.', ""));
else
dest[x] = original[x];
}
function send(){
var json = JSON.parse(document.getElementById("json").value);
var f = document.getElementById("filter").value;
var obj = {};
filter(json, obj, f);
document.getElementById("result").value = JSON.stringify(obj);
}
var d = {};
filter(a, d, "fare.legs.prop2");
console.log(d);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment