0

I have the following JSOn object ( Array of elements )

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"}
        ]
      }
    ]

I am trying to get ( and later remove.. ) an element with a specific label

I defined a where object

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

and I filter the object :

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

but I cannot get it : found = []

where am I wrong ?

thanks for feedback

3
  • el[where.key] is not an array in the sample data so _.isArray will return false Commented Nov 27, 2015 at 16:44
  • thanks ! I read it many times wo notice it ... too late in the night Commented Nov 28, 2015 at 8:13
  • add you comment as answer , if you want Commented Nov 28, 2015 at 10:32

1 Answer 1

1

try this

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

here is a working plunk

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.