0

I have a Javascript object

var a = {
    "tag1": "Stocks",
    "acctType1": "individual",
    "compare1": "contains",
    "match_name1": "scrapedaccounttype",
    "text1": "dog ",
    "tag2": "Stocks",
    "acctType2": "individual",
    "compare2": "contains",
    "match_name2": "scrapedaccounttype",
    "text2": "cat"
}

I need to use this Javascript object to do some more math, but I am not sure about how I would be iterating over the Javascript object.

I can have any number of tags (tag1, tag2, tag3, tag4 ... ) or similarly other keys like (acctType1, acctType2, acctType3.... ) so I need to iterate over them individually and do some manipulation to use these variables in a different function.

While , for each what would help my cause here. Note that I could have any number of tags(tag1,tag2...) or comapare(compare1, compare2, compare3..)

I would need to process all of them individually.

iConnor
  • 19,997
  • 14
  • 62
  • 97
rahul888
  • 413
  • 2
  • 8
  • 18

1 Answers1

3

What you have is NOT JSON. It is JavaScript defining an Object literal, commonly referred to as a JS object. JSON (JavaScript Object Notation) is a string that can be parsed to produce an object literal.

For your JS object (which has ample online documentation), you can iterate over the object keys by:

var a={"tag1":"Stocks","acctType1":"individual","compare1":"contains","match_name1":"scrapedaccounttype","text1":"dog ","tag2":"Stocks","acctType2":"individual","compare2":"contains","match_name2":"scrapedaccounttype","text2":"cat"}

Object.keys(a).forEach(function (k) {
  console.log(a[k]);
});

Or:

for (var key in a) {
  if (a.hasOwnProperty(key)) {
    console.log(a[k]);
  }
}
Charles Goodwin
  • 6,402
  • 3
  • 34
  • 63
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68