I need to filter JSON objects' properties and values based on a dynamic template (for security reasons). It is like viewing the JSON objects through a mask that is known only at run time.
Say I have this JSON object:
{ "id": "1",
"foo": [ "1", "2", "3" ],
"bar": [ "a", "b", "c"],
"fuzz": [ "y", "x" ]
}
And this template:
{ "id": "",
"fuzz": [ "y", "z"],
"foo": ""
}
Now I want to have the following result (applying the template onto the object):
{ "id": "1",
"fuzz": [ "y" ],
"foo": [ "1", "2", "3" ]
}
What are the best solutions to filter
Notes:
Based on the WiredPrairie's suggestion, I rewrote _.pick() and _.intersection() into the following method that does the trick:
// Loosely based on Underscore.js _.pick() method
function project(obj, tmp) {
var copy = {};
var keys = _.keys(tmp);
_.each(keys, function(key) {
if (key in obj) {
var vals = tmp[key];
if (Array.isArray(vals)) {
var copy_vals = [];
// Next lines could be replaced by:
// cvals = _.intersection(vals, obj[key]);
_.each(vals, function(val) {
if ($.inArray(val, obj[key])!=-1) {
copy_vals.push(val);
};
});
copy[key] = copy_vals;
} else {
copy[key] = obj[key];
};
};
});
return copy;
}
I'm not sure but you could try read this one jQuery.extend