Domanda

The following code grabs my data from a JSON object. The problem is that I can't seem to store what I want respectively in an array. I want my array to have the following structure:

Array = [0]['start'] = 'Date1', [0]['end'] = 'Date2', [0]['name'] = 'NameN'

etc. etc. the array index being nth length

So you can imagine multiple entries of this array, where I can access them by their index.

var array = new Array();
var label;

data = JSON.parse(data);
$.each(data.rows, function(i, row) {  
    $.each(row.c, function(j, item) {
        if(j == 0){
           label = 'start';
        }
        if(j == 1){
           label = 'end';
        }
        if(j == 2){
           label = 'name';
        }

        if(j == 0 || j == 1 || j == 2){
            array[i]["test"] = item.v;
            //console.log('array['+i+']['+label+'] = '+ item.v);
        }
        //console.log(item.v);
    });
});

Is there anyway to achieve this in JavaScript? Thanks

Edit: My original JSON

{"cols":[{"id":"","label":"start","pattern":"","type":"datetime"},{"id":"","label":"end","pattern":"","type":"datetime"},{"id":"","label":"content","pattern":"","type":"string"}],"rows":[{"c":[{"v":"Date(2014, 3, 25)","f":null},{"v":"Date(2014, 4, 2)","f":null},{"v":"Subgoal A","f":null}]},{"c":[{"v":"Date(2014, 4, 2)","f":null},{"v":"Date(2014, 4, 9)","f":null},{"v":"Subgoal B","f":null}]}],"p":null}
È stato utile?

Soluzione

There is no such thing as a multi-dimensional array in JavaScript. What you're looking for is an array of objects. Just create an output array, loop over the JSON and push a new object to the array.

var out = [];
for (var i = 0, l = data.rows.length; i < l; i++) {
  var row = data.rows[i].c;
  out.push({
    start: row[0].v,
    end: row[1].v,
    name: row[2].v
  });
}

for (var i = 0, l = out.length; i < l; i++) {
  console.log(out[i].start);
}

OUTPUT

Date(2014, 3, 25)
Date(2014, 4, 2)

DEMO

You can access the objects using the index, for example:

out[1] // { start="2014-12-13", end="2014-12-14", name="Mo2" }

You can even set up a function to retrieve any object based on its key and value:

function fetch(key, value) {
  return out.filter(function (el) {
    return el[key] === value;
  });
}

DEMO

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top