samedi 27 juin 2015

Undefined logic goes wrong

I am using hp on demand API, it will return an object as in this form for a postive query.

var obj = {
  "positive": [
    {
      "sentiment": "love",
      "topic": null,
      "score": 0.8053406931054015,
      "original_text": "I love you",
      "original_length": 10,
      "normalized_text": "I love you",
      "normalized_length": 10
    }
  ],
  "negative": [],
  "aggregate": {
    "sentiment": "positive",
    "score": 0.8053406931054015
  }
}

And it will return object like this for negative query

{
  "positive": [],
  "negative": [
    {
      "sentiment": "hate",
      "topic": null,
      "score": -0.8748623139495181,
      "original_text": "I hate you",
      "original_length": 10,
      "normalized_text": "I hate you",
      "normalized_length": 10
    }
  ],
  "aggregate": {
    "sentiment": "negative",
    "score": -0.8748623139495181
  }
}

And I am trying to assign property normalized_text to text, but there seems to be a logical error using undefined. Here is my code

var arr = ["I hate you", "I love you", "I miss you"];

var emotions = [];

for(var i=0; i<arr.length; i++){

//console.log(arr[i]);
    $.ajax({

  url: "http://ift.tt/1LNSEGi"+arr[i]+"&apikey=e3b26b74-bla"

  })
  .done(function( data ) {
    var obj = data;
    //emotions.push(obj.aggregate.sentiment);
    var text;
    if(typeof obj.positive[0].normalized_text === "undefined"){
        text = obj.negative[0].normalized_text;
    }else{
    text = obj.positive[0].normalized_text;
    }

    console.log(text);   
    console.log(obj.aggregate.sentiment);

  });

}

my error is cannot read normalized_text of undefined

Aucun commentaire:

Enregistrer un commentaire