Treat JSON by Javascript

Asked

Viewed 794 times

0

After ajax, my php return is:

[{"1":"4"},{"2":"3"},{"3":"7"}]

Data is variable in quantity and content.

I need to treat it by javascript and convert it into an array, in this format:

var retorno = [
    [1, 4],
    [2, 3],
    [3, 7]
];

I’m trying to:

var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){
    arr.push(parsed[x]);
}
alert(arr);

response is the variable with return data

But the result of Alert is: [object Object],[object Object],[object Object]

  • In this case, you are inserting an objetct into the same array... Parsed[x] will be, for example, {"1":"4"}, it is not clear to me which output you want, you want an array with the indices or an array with two members on each line of the array?

  • Oops, the format I need is what’s on the var retorno, each json item in an array line. Vlw

  • and buddy, I didn’t understand what you reported

2 answers

2


I created a array within the for by entering the key and the key value. See:

var parsed = JSON.parse('[{"1":"4"},{"2":"3"},{"3":"7"}]');
var arr = [];
for(var x in parsed){    
  arr.push([parseInt(x)+1, parseInt(parsed[x][parseInt(x)+1])]);
}

console.log(arr);

  • @snniffer made a change, just to simplify! If you have any more questions, just tap here! = D

1

I guess something like that

var response = '[{"1":"4"},{"2":"3"},{"3":"7"}]';
var parsed = JSON.parse(response);
var arr = [];
parsed.forEach(function(pvalue,index,ar){
    for(var pname in pvalue){
        arr.push([pname,pvalue[pname]]);
    }
});
console.log(arr);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.