Accessing an array in an array in javascript

I get a JSON response, for example:

[{
  "order_id": "12",
  "customer": "user user",
  "status": "Pending",
  "date_added": "02\/09\/2012",
  "total": "$500.00",
  "action": [{
    "text": "View",
    "href": "http:\/\/localhost\/oc\/admin\/index.php?route=sale\/order\/info&token=92a80574e5fcbf3e2d021404cfaae1a4&order_id=12"
  }]
}]

Look at the action key, this value again is an array. I try to get action key values ​​by following code, but it shows undefined to me

function (data) {
  if (data) {
    for (var i = 0; i < data.length; i++) {
      $('div.dashboard-content table.list tbody tr:first').before(
        '<tr id="' + 
        data[i]['order_id'] + 
        '"><td class="right">' + 
        data[i]['order_id'] + 
        '</td><td class="left">' + 
        data[i]['customer'] + 
        '</td><td class="left">' + 
        data[i]['status'] + 
        '</td><td class="left">' + 
        data[i]['date_added'] + 
        '</td><td class="right">' + 
        data[i]['total'] + 
        '</td><td class="right"> [<a href="' + 
        data[i]['action']['href'] + '">' + 
        data[i]['action']['text'] + 
        '</a>]</td></tr>'
      );
    }
  }
}

Can someone help me? Thanks in advance.

+5
source share
2 answers

As you said, actionthis is an array. Therefore, you cannot access it with data[i]['action']['href']. You should use an index to indicate the position of the array you want. For example, to access the first position, you should use:

var href = data[i].action[0].href;
var text = data[i].action[0].text;
+5
source

action- An array containing an object with a property called text. Change:

data[i]['action']['text']

at

data[i]['action'][0]['text']
+3
source

All Articles