user3144542
user3144542

Reputation: 599

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.

$.each(responseData, function(k1,v1){
            if(k1 == "0"){
                $.each(v1, function(k2,v2){
                    $.each(v2, function(k3, v3){
                        if(k3 == "val"){
                          //store in object here
                          //Array1 = array("time"=>k2, "iVal"=>v3)
                          console.log(k3 + v3 + k2);
                        }else{
                           //Array2 = array("time"=>k2, "aVal"=>v3)
                           console.log(k3 + v3 + k2);
                        }
                    });
                });
            }
});

So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:

//obj created outside

obj1.date = k2;
obj2.iVal = v3;

But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?

Edit: Added input and output desired.

Input

{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}

Desired output

array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}

Upvotes: 1

Views: 3039

Answers (2)

Royi Namir
Royi Namir

Reputation: 148524

try this :

var g1=[];
var g2=[];


for ( a in o[0])
  {
    g1.push({time:a , iVal:o[0][a]['iVal']})
    g2.push({time:a , aVal:o[0][a]['aVal']})

}

http://jsbin.com/qividoti/3/edit

enter image description here

Upvotes: 1

alex
alex

Reputation: 644

a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.

from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either

the js way -> dot notation

var obj = JSON.parse(jsonStirng);
var value = obj.value;

or like a php array

var value = obj["value"];

Upvotes: 0

Related Questions