0

让我们看看,我有一个 jquery 解析的 json 对象,它是这样的(但非常大):

[
{answered: 0,
caller: 4,
callid: 4,
expired: 0,
groupid: 2,
location: "jubin",
name: "vahid",
personid: 3,
presense: 1367323732,
response: null,
text: null,
time: 1367336754,
type: 0},

{answered: 0,
caller: 6,
callid: 5,
expired: 0,
groupid: 2,
location: "jubin",
name: "vahid",
personid: 3,
presense: 1367323732,
response: null,
text: null,
time: 1367336766,
type: 0},

{answered: 0,
caller: 4,
callid: 4,
expired: 0,
groupid: 2,
location: "jubin",
name: "reza",
personid: 1,
presense: 1367392633,
response: null,
text: null,
time: 1367336754,
type: 0},

{answered: 0,
caller: 6,
callid: 5,
expired: 0,
groupid: 2,
location: "jubin",
name: null,
personid: 1,
presense: 1367392633,
response: null,
text: null,
time: 1367336766,
type: 0}
] 

我喜欢这样的东西(短版):

[
{
callid: 4,
name: {"vahid", "reza"}
},

{
callid: 5,
name: {"vahid", null}
} 
] 

任何人都可以帮忙吗,
我几乎尝试了所有的事情,但我肯定在某个地方做错了,谢谢转发

4

2 回答 2

1

尝试使用_http://jsfiddle.net/sWDsM/3/

这将转换data为一个数组,如arr[callid] = [name, ...]

var arr = _.inject(data, function (memo, row) {
    memo[row.callid] || (memo[row.callid] = []);
    if (row.name != null && memo[row.callid].indexOf(row.name) == -1) {
        memo[row.callid].push(row.name);
    }
    return memo;
}, []);

这将转换为您所期望的

var result = [];
for (var key in arr) {
    result.push({callid: key, name: arr[key]});
}
于 2013-05-07T09:22:48.783 回答
0

万岁,我做到了!
这是我的结果:

function calllog(log){//given log is my primary array
    var oLog = [];
    var tmpLog = [];
    var LL = log.length;
    for (var i=0; i<LL; i++){
        var thisID = log[i].callid;
        if(oLog.indexOf(thisID)<0){
            oLog.push(thisID);
        }
    };
    for (j in oLog){
        var tmpholder = [];
        for (k in log){
            if (oLog[j] == log[k].callid){
                tmpholder.push(log[k].name);
            }
        }
        tmpLog.push({
            'callid': oLog[j], 'name': tmpholder
        })
    };
    $(document.body).data('calllog', tmpLog);
};
于 2013-05-05T06:49:54.310 回答