-1

The JSON I have:

[{"one":"a","two":"1","three":"2","four":"3"},
 {"one":"b","two":"4","three":"5","four":"6"},
 {"one":"c","two":"7","three":"8","four":"9"}]

The array that I need:

[[[1,"a"], [4,"b"], [7,"c"]],
 [[2,"a"], [5,"b"], [8,"c"]],
 [[3,"a"], [6,"b"], [9,"c"]]]

How can I treat the JSON to transform it in an array of arrays?

I need to do it dynamically because the JSON could be bigger (more rows a, b, c, ...z). The 4 columns are fixed(one,two,three,four) and won't change.

I have tried several ways...to do it with .push, creating an array=[[]], trying array=new array(3) and then in each position making array[0]=new array[], but i didn't solved yet, I have passed all day trying this, all day!

I think the solution is using push like here related subject But I don't understand this solution very well.

I would appreciate your help please.

Community
  • 1
  • 1
rudy cobos
  • 13
  • 5

2 Answers2

0

In your json its array inside array so the first array is of single item and the second array is for 3 item. So you need to write the inner for loop for getting the second array 2 items like below.

for(var i=0; i<info.length; i++)
{
    for(var j=0; j<info[i].length; j++)
    {
        Ti.API.info("Title : " + sample[i][j].one);
        Ti.API.info("Desc : " + sample[i][j].a);
    }
}
  • Thank you for your response but i don't have the problem moving inside the array (i can do it with $.each(resultado, function( key, value ) The problem that I have is --> how to build the new array – rudy cobos Apr 01 '15 at 21:49
0

You can map the rows and columns, like below:

http://jsfiddle.net/Castrolol/0x8u352r/1/

var sampleData = [{"one":"a","two":"1","three":"2","four":"3"},
 {"one":"b","two":"4","three":"5","four":"6"},
 {"one":"c","two":"7","three":"8","four":"9"}];


function transform(data){

    var prepared = data.map(function(row){
        var keys = Object.keys(row);
        var values = keys.map(function(key){
            return row[key];
        });
        var columnOne = values[0];
        var otherColumns = values.slice(1);

        return {
            letter: columnOne,
            numbers: otherColumns
        };

    });    

    var rows = [];

    prepared.forEach(function(row){

        row.numbers.forEach(function(number, i){

            if( i >= rows.length ){
                rows.push([]);
            }

            rows[i].push([+number, row.letter]);

        });

    });    

    return rows;

}


var result =  transform(sampleData) ;
console.log(JSON.stringify(result, null, 4));
Luan Castro
  • 1,184
  • 7
  • 14