mardi 6 février 2018

Include if..else... statement in JS forEach method?

While trying to update a dictionary inside the iterator I got the error "SyntaxError: expected expression, got keyword 'if'"

The ut_frequencies data looks like:

{ "_id" : "app1", "cnt" : 3422 }
{ "_id" : "app2", "cnt" : 2752 }
{ "_id" : "app3", "cnt" : 2736 }
{ "_id" : "app4", "cnt" : 2711 }

Which I suppose is a list of dictionaries. I want to check if the app is already in the data dictionary and if so, update the "utf" value, if not, then add a new item only with the "utf" attribute set.

ut_frequencies.forEach(item=> 
  if(item._id in data){
    data[item._id]["utf"] = item.cnt;

  }else{
    data[item._id] = {utf: item.cnt, atf: 0, ptf: 0};
  }
)

Which is the best way to solve this.

Aucun commentaire:

Enregistrer un commentaire