重构JSON对象

时间:2013-08-05 07:26:49

标签: javascript json

我有以下数组:

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"}
    ]
}

现在我想从上面创建一个json数组,其值为data到另一个json 这将是:

[
    {
        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]
    }
]

我尝试过如下:

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+'},';
    }
}

你能指导我怎么做吗? 提前谢谢。

5 个答案:

答案 0 :(得分:1)

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示例输出:

[{"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"]]}]

答案 1 :(得分:0)

我猜cumulative_key处于错误的循环中:

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']+"],";
}

您应该考虑操作实数组对象,然后再进行json编码。

答案 2 :(得分:0)

使用这些功能

json_decode

get_object_vars

答案 3 :(得分:0)

试试这段代码......

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

答案 4 :(得分:0)

出于多样性的考虑,略有不同的解决方案

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

结果是

 [{"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"]]}
  ]

我略微“混洗”了输入数据,只是为了避免错误地假设总是对数据进行排序...在编写此代码段时,我几乎陷入了两次。

相关问题