2

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.

4
  • 1
    Your input is not JSON. JavaScript!=JSON. And your code is not PHP. Commented Aug 5, 2013 at 7:31
  • you should note that the structure you want to achieve isn't valid JSON... Nor is your input, btw... Commented Aug 5, 2013 at 7:31
  • The better way to create JSON in JS is to create an object or array and convert it to JSON with JSON.stringify. Building the JSON manually (like you do) is error prone. For example, keys must be in double quotes in JSON, and you have key: instead of "key": in your string. If you don't want to create JSON at all, but just convert your object into an array of objects, then say so. But that has nothing to do with JSON then. Also, what's the problem with the code you have? Please explain. Commented Aug 5, 2013 at 7:42
  • @Felix Its not in grouped and moreover the time_val is showing repeatedly for a particular assignedTo. Commented Aug 5, 2013 at 7:45

5 Answers 5

1

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"]]}]
Sign up to request clarification or add additional context in comments.

4 Comments

Instead of of saving the array index in temp_keys, you could just save the object (that you add to the array) itself.
@FelixKling, yes i could, but i did not do that only because in question was wanted output as an array. If i create temp as object {} then i need to convert it into array later in order json.stringify would give me wanted result as an array. Also tought that mabye its easier to read in current way not sure tough.
No, I'm talking about tmp_keys. Instead of storing id -> index you could store id -> obj and then you could just do: temp_keys[res.data[i]['assignedTo']]['values'].push([res.data[i]['createdDate'], res.data[i]['count']]);, i.e. you avoid accessing both, temp and temp_keys.
Thanks for this! But if the data source is not sorted by keys, you'll get duplicates with this code of yours. I was getting duplicate keys so rather than if (!temp_keys[res.data[i]['assignedTo']]) I used if (typeof temp_keys[res.data[i]['assignedTo']] == "undefined") and all was dandy.
0

use these functions

json_decode

get_object_vars

1 Comment

OP is using JavaScript, not PHP.
0

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.

6 Comments

thanks for the clarification. Actually I have to do all in js not in php. But two issues are there first of all time_val are repeating whenever I am trying to print the value of cumulative_val outside of the for loop. second thing is that all the date and count should be groupwise and group by assignedTo.
Then don't put [php] tag in your post if you're not talking about it :p Does your array is sorted by "assignedTo" values?
I would create appropriate class for this JSON packet, create assignment constructor and pack objects of this class in some data structure (array, for example).
No its not. It directly fetch from database. But I can do in a sorted order.
Try my updated code. May need some ajustments but the logic is here.
|
0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.