Check an obj json option and return

1

Good afternoon, guys. I'm starting now with angular 2 and I'm having a problem. I have a json object and within that obj, I have several inputs and I want to filter by the colors I get in this obj.

json example:

public alerts = [
{      text: 'lorem ipsum', color: 'green'
},
{      text: 'lorem ipsum', color: 'yellow'
},
{      text: 'lorem ipsum', color: 'red'
},
{      text: 'lorem ipsum' }]

I'm trying to filter through the colors to know which variable I'm going to put the return on. I'm trying to do this:

for(let i = 0; i < this.alerts.length; i++) {
  let obj = this.alerts[i];
  console.log(obj)
  if(this.alerts[i].color == 'green'){
    this.normal= this.alerts[i]
  }else{
    this.attention = this.alerts[i]
  }
}

But it is not working as I want, I want to separate in these 2 variables, attention and normal, doing the verification. Saying that when the color goes "green" the json of it, goes to the normal variable.

    
asked by anonymous 20.08.2017 / 17:19

1 answer

1

javascript already provides the filter :

var normal = alerts.filter(function( obj ) {
  return obj.color == "green";
});

and for attention:

var attention = alerts.filter(function( obj ) {
  return obj.color != "green";
});
    
20.08.2017 / 17:56