user3873833
user3873833

Reputation: 55

how to filter on a JavaScript object based on its attributes

I have a JavaScript object

 var items = { ids : [
  {
    label: "red",
    complete: true
  },
  {
    label: "green",
    complete: false
  },
  {
    label: "blue",
    complete: true
  }
]

}

I need to filter out based on the complete attribute when I click on the complete button or when I click on all button it show show me all the entries.

How can I do this in the same function

I have this function which takes the list DOM element and creates the entries accordingly. I am wondering how could I write this function such that it could filter on the complete status or print all the entries in the redraw function itself.

 var redraw = function(items) {
     list.innerHTML='';
     for (var id in items) {
       draw(model.todos[id], list);
     }
 };

  var draw = function(Obj, container) {
      var el = Template.cloneNode(true);
      el.setAttribute('data-id', Obj.id);
      container.appendChild(el);
       update(Obj);
});

}

Upvotes: 2

Views: 98

Answers (3)

Prabhu Murthy
Prabhu Murthy

Reputation: 9271

var result = [];

for(var item in items.ids){
  if(items.ids[item].hasOwnProperty("complete") && 
     items.ids[item].complete === true){
    result.push(item);
  }
}

you can use this to filter out the items based on the complete attribute.

demo

Upvotes: 1

Andy
Andy

Reputation: 63587

Add a new function called filterItems that accepts the items array and key and value parameters and returns a filtered array based on those parameters. Then, just call it from redraw with the correct arguments.

function filterItems(items, key, value) {
  return items.ids.filter(function (el) {
    return el[key] === value;
  });
}

var redraw = function(items) {
  list.innerHTML='';
  items = filterItems(items, 'complete', true);
  for (var id in items) {
    draw(model.todos[id], list);
  }
};

DEMO

Upvotes: 1

Joseph Spens
Joseph Spens

Reputation: 664

If you're using Underscore, this is pretty simple

var completedItems = {
  ids: _.filter(items.ids, function (id) { return id.complete; })
};

Otherwise you could write it by hand

var completedItems = {
  ids: (function (ids) {
    var arr = [];
    ids.forEach(function (id) {
      if (id.complete) arr.push(id);
    });
    return arr;
  })(items.ids)
};

Upvotes: 1

Related Questions