Underscorejs:如何按属性删除嵌套对象?

时间:2014-04-01 13:53:49

标签: javascript underscore.js lodash

我有一个示例嵌套菜单。我想删除具有所选属性的对象。我怎么用下划线或lodash这样做? THX

[
{
"label": "My Documents",
"id": "mydocs",
"children": [
  {
    "children": [
      {
        "children": [

        ],
        "label": "sub folder 1.1",
        "id": "58d32eec-75d3-45ab-b896-73bdb12dcacd",
        "selected": "selected"
      },
      {
        "children": [
          {
            "children": [

            ],
            "label": "sub sub folder 1.2.1",
            "id": "0c0c9705-7012-4e11-a540-526babdd816f"
          }
        ],
        "label": "sub folder 1.2",
        "id": "bdfa6eb9-9527-490a-be5d-b2158df98982"
      }
    ],
    "label": "folder 1",
    "id": "e53455ef-4e0c-4d2c-8148-7e3152fff0ae"
  },
  {
    "children": [

    ],
    "label": "folder 2",
    "id": "b6fa392b-89ed-441f-9c4b-2a44c48829f6"
  },
  {
    "children": [

    ],
    "label": "My Docs 2",
    "id": "db92b3e6-80f6-4344-bba1-252b195c17a0"
  }
]
}
]

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情。

arr = _.without(arr, _.findWhere(arr.children, {selected: 'selected'}));

http://underscorejs.org/#without

答案 1 :(得分:1)

这将删除data数组中的项data是您的给定对象。

_.each(data, function(item, idx) {
  if(_.findWhere(item.children, {selected: "selected"})) {
    data.splice(idx, 1); //remove this item from data
  }
});

这将从数组中筛选出所选对象仍将在数据中的数据

_.reject(data, function(item, idx) {
  return _.findWhere(item.children, {selected: "selected"});
});