How to split JSON values if it contains "Most_Likely"?

0

Issue

I am trying to parse through JSON values and parse what I need.

Basically, I only want to capture values that are denoted as "Most_Likely".

In addition, if there is an OR statement, I need to separate out those values.

Here is my attempt at doing this, but I’m getting a JS error :

for (i = 0; i < obj1.Summary.length; i++) {


for (j in obj1.Summary[i]) {
    
    if (j.indexOf('Most_Likely') && obj1.Summary[i][j].indexOf('|OR|') >= 0){
        var tempvalue = obj1.Summary[i][j].indexOf('Most_Likely').split(" |OR| ");
        attributesvalues.push(tempvalue);
        alert(attributesvalues);
    }
    else{
    //do nothing
    }
    
    
   }

}

//sample JSON

var obj1 = {
 "Summary" : 
    [
        {
            "host:Most_Likely" : "www.google.com", 
            "host:Indicative" : "www.yahoo.com |OR| www.google.com", 
            "term:Most_Likely" : "cars" |OR| new cars |OR| SUVs, 
            "term:Indicative" : "automatic |OR| Lexus |OR| SUVs |OR| Civic" 
        }
    ]
 };

Solution

Error in this line

var tempvalue = obj1.Summary[i][j].indexOf('Most_Likely').split(" |OR| ");

indexOf returns position (type number), split there is in String object that’s why you get error.

var attributesvalues = [],
    tempvalue;

for (var i = 0; i < obj1.Summary.length; i++) {
  for (var j in obj1.Summary[i]) {
    if (j.indexOf('Most_Likely') >= 0 && obj1.Summary[i][j].indexOf('|OR|') >= 0) {
      tempvalue = obj1.Summary[i][j].split(" |OR| ");
      attributesvalues.push(tempvalue);
    } else { 
    }
  }
}

console.log(attributesvalues);

Answered By – Oleksandr T.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More