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: "[email protected]", 3_email: "[email protected]"…}

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

1_email: "[email protected]"
1_status: "invalid"
1_type: "alpha.domain.com"
2_email: "[email protected]"
2_status: "invalid"
2_type: "bravo.domain.com"
3_email: "[email protected]"
3_status: "invalid"
3_type: "charlie.domain.com"
4_email: "[email protected]"
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 [email protected] 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.

0

1 Answer 1

3

You could do this with an indexer.

test[i + '_email']
Sign up to request clarification or add additional context in comments.

2 Comments

That works perfectly, I have never used indexing outside of test[i] so I didn't even think of that. Thanks a Ton :)
In javascript x[y] is not indexing. It's property access.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.