0

除了我在不同级别指定的一些属性之外,我如何从我的 JSON 中修剪所有内容,同时保持我的节点结构和数组结构?

我查看了 Underscore.js,似乎它没有那么多细粒度的控制来保留节点结构。在下面的示例中,理想情况下,我希望能够指定'_id', 'revisions[0]._id', 'revisions[0]._clientHasViewed'为保留这些属性的参数。

当然有一个简单的方法可以做到这一点。这就是我要找的东西:

原来的

{
    "_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"
}

修剪过的

{
    "_id": "50cbf5214ffaee8f0400000a",
    "revisions": [
        {
            "_id": "50cbfae65c9d160506000007",
            "clientHasViewed": false,
        },
    ],
}
4

1 回答 1

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;
};

例如

var trimmed = copyTo({}, original, '_id,');
    trimmed.revisions = [{}];
    trimmed = copyTo(trimmed.revisions[0], original.revisions[0], '_id,_clientHasViewed,'); 
于 2012-12-28T22:34:55.727 回答