Mausumi
Mausumi

Reputation: 431

Restructure JSON object

I have the following array:

var res = {
    "status": "Success",
    "data": [
        {"assignedTo":"0", "createdDate":"23-07-2013", "count":"2"}, 
        {"assignedTo":"182398", "createdDate":"01-08-2013", "count":"2"},
        {"assignedTo":"182398", "createdDate":"23-07-2013", "count":"2"}, 
        {"assignedTo":"182398", "createdDate":"24-07-2013", "count":"12"}, 
        {"assignedTo":"182398", "createdDate":"22-07-2013", "count":"1"},
        {"assignedTo":"182398", "createdDate":"30-07-2013", "count":"4"},
        {"assignedTo":"182398", "createdDate":"31-07-2013", "count":"19"},
        {"assignedTo":"185271", "createdDate":"24-07-2013", "count":"2"},
        {"assignedTo":"185271", "createdDate":"23-07-2013", "count":"1"}
    ]
}

Now I want to make one json array from the above with the value of data to another json which will be like:

[
    {
        key: "0",
        values: [["23-07-2013", 2]]
    },
    {
        key: "182398",
        values: [["01-08-2013", 2],
                 ["23-07-2013", 2],
                 ["24-07-2013", 12],
                 ["22-07-2013", 1],
                 ["30-7-2013", 4],
                 ["31-7-2013", 19]
    },
    {
        key: "185271",
        values: [["24-07-2013", 2],
                 ["23-07-2013", 1]
    }
]

I have tried like the following:

for (i in res.data) {
    for (k in res.data[i]) {
        time_val += "[" + res.data[i]['createdDate'] + ","
                    + res.data[i]['count'] + "],";
        cumulative_val += '{key:"' + res.data[i]['assignedTo']
                          + '",values:'+time_val+'},';
    }
}

Could you please guide me how to do this? Thanks in advance.

Upvotes: 2

Views: 2895

Answers (5)

Gergely M
Gergely M

Reputation: 733

A slightly different solution just for the sake of variety

let res = {
    "status": "Success", "data": [
        {"assignedTo": "185271", "createdDate": "23-07-2013", "count": "1"},
        {"assignedTo": "182398", "createdDate": "01-08-2013", "count": "2"},
        {"assignedTo": "182398", "createdDate": "23-07-2013", "count": "2"},
        {"assignedTo": "182398", "createdDate": "24-07-2013", "count": "12"},
        {"assignedTo": "185271", "createdDate": "24-07-2013", "count": "2"},
        {"assignedTo": "182398", "createdDate": "22-07-2013", "count": "1"},
        {"assignedTo": "0", "createdDate": "23-07-2013", "count": "2"},
        {"assignedTo": "182398", "createdDate": "30-07-2013", "count": "4"},
        {"assignedTo": "182398", "createdDate": "31-07-2013", "count": "19"},
        ]
};

let values = [];
let ctrl = '';
let interim = {};

for (const obj of res.data) {
    const id = obj.assignedTo;
    values = interim[obj.assignedTo] ? interim[obj.assignedTo].values : [];
    values.push([obj.createdDate, obj.count])
    interim[obj.assignedTo] = {"key": obj.assignedTo, "values": values};
    ctrl = ctrl !== id ? id : ctrl;
}

let reshaped = Object.values(interim);

console.log(JSON.stringify(reshaped, null, 0));

and the result is

 [{"key": "0", "values": [["23-07-2013", "2"]]},
  {"key": "182398", "values": [["01-08-2013", "2"],
                               ["23-07-2013", "2"],
                               ["24-07-2013", "12"],
                               ["22-07-2013", "1"],
                               ["30-07-2013", "4"],
                               ["31-07-2013", "19"]]},
  {"key": "185271", "values": [["23-07-2013", "1"],
                               ["24-07-2013", "2"]]}
  ]

I "shuffled" the input data a bit just to avoid a mistake of assuming the data is always sorted... which I almost fell into twice while was writing up this snippet.

Upvotes: 0

chakroun yesser
chakroun yesser

Reputation: 1497

Try this code...

var _root = new Array();
        for (i in res.data) {
            for (k in res.data[i]) {
                var _child  = [res.data[i]['createdDate'], res.data[i]['count']];
                var _parent = [{"key":res.data[i]['assignedTo'], "values": _child}];
            }
           _root.push(_parent); 
        }
        var _JSON_ = JSON.stringify(_root);

Upvotes: 0

Aivar
Aivar

Reputation: 2029

Something like this in javascript:

var res = {"status":"Success","data":[{"assignedTo":"0","createdDate":"23-07-2013","count":"2"}, 
                               {"assignedTo":"182398","createdDate":"01-08-2013","count":"2"},
                              {"assignedTo":"182398","createdDate":"23-07-2013","count":"2"}, 
                             {"assignedTo":"182398","createdDate":"24-07-2013","count":"12"}, 
                              {"assignedTo":"182398","createdDate":"22-07-2013","count":"1"},
                              {"assignedTo":"182398","createdDate":"30-07-2013","count":"4"},
                              {"assignedTo":"182398","createdDate":"31-07-2013","count":"19"},
                              {"assignedTo":"185271","createdDate":"24-07-2013","count":"2"},
                              {"assignedTo":"185271","createdDate":"23-07-2013","count":"1"}]
}
//Wanted mixed object
var temp = [];
//Store keys, so we do not need to check from temp if key allready exists
var temp_keys = {};
//Loop trough data
for (var i in res.data)
{
    //Check if key is allready stored in object
    if (!temp_keys[res.data[i]['assignedTo']])
    {
        //Store new key, and save it''s position
        temp_keys[res.data[i]['assignedTo']] = temp.length;
        //Create new array element as new object
        temp.push(
            {
                'key' : res.data[i]['assignedTo'],
                'values': []
            }
        );
    }
    //Save values into correct position
    temp[temp_keys[res.data[i]['assignedTo']]]['values'].push([res.data[i]['createdDate'], res.data[i]['count']]);
}
console.log(temp);
console.log(JSON.stringify(temp));

JSON Example Output:

[{"key":"0","values":[["23-07-2013","2"]]},{"key":"182398","values":[["01-08-2013","2"],["23-07-2013","2"],["24-07-2013","12"],["22-07-2013","1"],["30-07-2013","4"],["31-07-2013","19"]]},{"key":"185271","values":[["24-07-2013","2"],["23-07-2013","1"]]}]

Upvotes: 1

Maxime Lorant
Maxime Lorant

Reputation: 36181

I guess that the cumulative_key is in the wrong loop:

lastKey = res.data[0]['assignedTo'];
for(i in res.data) {
    if(res.data[i]['assignedTo'] != last) {
        cumulative_val += '{key:"'+res.data[i]['assignedTo']+'",values:'+time_val+'},';
    }
    time_val += "["+res.data[i]['createdDate']+","+res.data[i]['count']+"],";
}

You should think about manipulate real array object and then after make a json encoding.

Upvotes: 0

user2366009
user2366009

Reputation:

use these functions

json_decode

get_object_vars

Upvotes: 0

Related Questions