Check an obj json option and return

Asked

Viewed 27 times

1

Good afternoon, you guys. I’m starting now with Angular 2 and I’m having a problem. I have a json object and inside this obj, I have several inputs and I want to filter by the colors I get in this obj.

Example of json:

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

I am trying to filter through the colors to know in which variable I will put the return. I am trying to do so:

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 this not working as I want, I want to separate in these 2 variables, Attention and normal, doing the check. Saying that when the color is "green" her json, goes to the normal variable.

  • The way it is, normal: {"text":"lorem ipsum","color":"green"} and attention: {"text":"lorem ipsum"}. What’s wrong with it?

  • Pq the error template, complaining that it does not accept the array. Cannot find a differ supporting Object '[Object Object]' of type 'Object'. Ngfor only Supports Binding to Iterables such as Arrays.

1 answer

1


The javascript already provides the function filter:

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

and for Attention:

var attention = alerts.filter(function( obj ) {
  return obj.color != "green";
});
  • that solved, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.