Jackbeeby
Jackbeeby

Reputation: 93

Dynamically updating variable name

I am retrieving Json within jquery using Ajax. My Json array format:

{"date":[{"day1":"13","day2":"14"...etc}]}

There is multiple date arrays (Only showing one for example). In jquery, I retrieve the code by:

response.date[dateCount].day1

Where response is the json, dateCount auto increments. Although I need another while statement to auto increment the day. So changes to day1, day2, etc.

I cannot just have each element in the date array without an assigned day. 13 needs to correspond to date1 etc.

I have tried using eval and window to dynamically change the variable, although, I cannot seem to figure out a method that allows me to auto increment this variable without assigning data to it.

Upvotes: 0

Views: 34

Answers (1)

Akshay
Akshay

Reputation: 14348

You can retrieve the keys of the object using Object.keys() and then use the index to fetch the data or you can get a value by using the format object["key"]

const response = {
  "date": [{
    "day1": "13",
    "day2": "14",
    "day3": "15"
  }]
}

const firstDate = response.date[0];
const dateKeys = Object.keys(firstDate);

console.log(dateKeys);

console.log(firstDate[dateKeys[0]]);

console.log(firstDate[`day${1}`])

Upvotes: 3

Related Questions