除了我在不同级别指定的一些属性,同时保留我的节点结构和数组结构外,我如何修剪JSON中的所有内容?
我查看了Underscore.js,看起来它没有那么多细粒度控制来保留节点结构。在下面的示例中,理想情况下,我希望能够将'_id', 'revisions[0]._id', 'revisions[0]._clientHasViewed'
指定为保留这些属性的参数。
当然有一种简单的方法可以做到这一点。这就是我要找的东西:
ORIGINAL
{
"_id": "50cbf5214ffaee8f0400000a",
"_user": "50b1a966c12ef0c426000007",
"expenses": [],
"name": "Untitled Project",
"payments": [],
"revisions": [
{
"_id": "50cbfae65c9d160506000007",
"clientHasViewed": false,
"comments": [],
"dateCreated": "2012-12-15T04:21:58.605Z"
},
{
"_id": "50cbfae65c9d160506000008",
"clientHasViewed": false,
"comments": [],
"dateCreated": "2012-12-15T04:21:58.605Z"
}
],
"status": "Revised",
"thumbURL": "/50cd3107845d90ab28000007/thumb.jpg"
}
TRIMMED
{
"_id": "50cbf5214ffaee8f0400000a",
"revisions": [
{
"_id": "50cbfae65c9d160506000007",
"clientHasViewed": false,
},
],
}
答案 0 :(得分:1)
ExtJs有一个copyTo函数(只有一个级别),但你可以用AngularJs创建类似的东西(angular有angular.copy,但是复制了整个对象):
var copyTo = function(dest, source, names){
names = names.split(/[,;\s]/);
angular.forEach(names, function(name){
if(source.hasOwnProperty(name)){
dest[name] = source[name];
}
});
return dest;
};
E.g。
var trimmed = copyTo({}, original, '_id,');
trimmed.revisions = [{}];
trimmed = copyTo(trimmed.revisions[0], original.revisions[0], '_id,_clientHasViewed,');