我需要根据动态模板过滤JSON对象的属性和值(出于安全原因)。这就像通过仅在运行时知道的掩码查看JSON对象。
说我有这个JSON对象:
{ "id": "1",
"foo": [ "1", "2", "3" ],
"bar": [ "a", "b", "c"],
"fuzz": [ "y", "x" ]
}
这个模板:
{ "id": "",
"fuzz": [ "y", "z"],
"foo": ""
}
现在我希望得到以下结果(将模板应用到对象上):
{ "id": "1",
"fuzz": [ "y" ],
"foo": [ "1", "2", "3" ]
}
过滤的最佳解决方案
注意:
答案 0 :(得分:0)
根据WiredPrairie的建议,我将_.pick()和_.intersection()重写为以下方法:
// 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;
}
答案 1 :(得分:-1)
我不确定,但您可以尝试阅读此jQuery.extend