underscore.js如何使用_.filter从JSON对象获取元素

时间:2015-11-27 15:33:28

标签: json underscore.js

我有以下JSOn对象(元素数组)

var roles = [
      {
        "label": "alpha",
        "children": [
          {"label": "role1","title": "role1","value": "1"},
          {"label": "role2","title": "role2","value": "2"}
        ]
      },

      {
        "label": "beta",
        "children": [
          {"label": "role3","title": "role3","value": "3"},
          {"label": "role4","title": "role4","value": "4"}
        ]
      },

      {
        "label": "delta",
        "children": [
          {"label": "role5","title": "role5","value": "5"},
          {"label": "role6","title": "role6","value": "6"}
        ]
      }
    ]

我试图获取(以后删除..)具有特定标签的元素

我定义了一个where对象

var where = {key: 'label', value:"alpha"};  

我过滤了对象:

var filteredRoles = _.filter(roles, function (el) {
  return el[where.key] && _.isArray(el[where.key]) &&
       _.indexOf(el[where.key], where.value) >= 0;
});
console.log("found "+JSON.stringify(filteredRoles, null, 2));

但我无法得到它:found = []

我哪里错了?

感谢您的反馈

1 个答案:

答案 0 :(得分:0)

试试这个

var result = _.filter(roles, function(role) {
   return (role[where.key] === where.value) && _.isArray(role['children']);
})

这是一个有效的plunk