0

I am working with an API returning a response to me via AJAX, it returns the response in responseJSON so I access the part of the object I need with dot notation just like with any other AJAX call

var test = jqxhr.responseJSON.test;

A literal representation of the object would be:

test = {1_status: "invalid", 4_type: "domain.com", 1_type: "alpha.domain.com", 4_email: "admin@domain.com", 3_email: "admin@charlie.domain.com"…}

Which appears as so in the console after a console.log(test)

1_email: "admin@alpha.domain.com"
1_status: "invalid"
1_type: "alpha.domain.com"
2_email: "admin@bravo.domain.com"
2_status: "invalid"
2_type: "bravo.domain.com"
3_email: "admin@charlie.domain.com"
3_status: "invalid"
3_type: "charlie.domain.com"
4_email: "admin@domain.com"
4_status: "invalid"
4_type: "domain.com"
errorCode: "0"

How would I access the values by key like 1_email in a for loop interation like below.

for (var i = 1; i <= 4; i++){
  // access key values here like so:
  //console.log(test.i_email);
  // where the console should return admin@alpha.domain.com on the first interation
}

If I simply do something like the below outside the loop where I manually call a certain key:

console.log(test.1_email);

I get the following:

Uncaught SyntaxError: Unexpected token ILLEGAL 

I need to access each piece with [i]_status as I do not know the exact return values and the order changes, and unfortunately I do not have access to the API directly.

Any help is appreciated.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
MattSizzle
  • 3,145
  • 1
  • 22
  • 42

1 Answers1

3

You could do this with an indexer.

test[i + '_email']
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445