在JavaScript中转换对象

时间:2013-03-24 16:25:41

标签: javascript

我有一个结构为的对象:

[ {"vid":"aaa", "san":12}, 
  {"vid":"aaa", "san":18}, 
  {"vid":"aaa", "san":2}, 
  {"vid":"bbb", "san":33}, 
  {"vid":"bbb", "san":44}, 
  {"vid":"aaa", "san":100}]

此对象作为SerializeData(inData)变量传递给名为inData的函数:

function SerializeResults( inData ) {
    $.each( inData, function( i, val ) {
    });
} 

我想迭代inData中的所有对象并对其进行转换,因此在结果中我得到一个具有如下结构的对象:

[ { "vid":"aaa","san":[12,18,2,100] }, 
  { "vid":"bbb","san":[33,44] } ]

我该怎么做?

4 个答案:

答案 0 :(得分:2)

你去了:http://jsfiddle.net/hezgb/

    var data = [ {"vid":"aaa", "san":12}, {"vid":"aaa", "san":18}, {"vid":"aaa", "san":2}, {"vid":"bbb", "san":33}, {"vid":"bbb", "san":44}, {"vid":"aaa", "san":100}];

function SerializeResults( inData ) {

    var map = {};
    $.each( inData, function( i, val ) {
         if(!map[val.vid]){
             var o = {};
             o.san = [];
             map[val.vid] = o;
         }
        else{
            var o = map[val.vid];
        }

        o.san.push(val.san);
    });
    var main = [];
    $.each( map, function( key, val ) {
        main.push({vid:key,san:val.san});  
    });

    return main;
}

console.log(SerializeResults(data));

答案 1 :(得分:1)

这对你有什么用?

http://jsfiddle.net/T7bZd/4/

    $.each( inData, function( i, val ) 
{
   if(typeof out[val.vid]==="undefined")
       out[val.vid] = new Array();
   out[val.vid].push(val.san);
});

答案 2 :(得分:0)

这个怎么样......

function SerializeResults( inData ) {
var a = {};

$.each(inData, function( i, val ) {
    var id = val['vid'];

    if (a[id]) {
        a[id]['san'].push(val['san']);
    } else {
        a[id] = {vid:id, san:[val['san']]};
    }
});

var aa = [];

$.each(a, function(i, val) {
    aa.push(val);
});

return aa;

}

答案 3 :(得分:0)

我正在添加另一个答案,作为一种惩罚形式,你会问“我该怎么做?” ; - )

var _ = require('underscore')
var json = '[ {"vid":"aaa", "san":12}, {"vid":"aaa", "san":18}, {"vid":"aaa", "san":2}, {"vid":"bbb", "san":33}, {"vid":"bbb", "san":44}, {"vid":"aaa", "san":100}]'

var grouped = _.groupBy(JSON.parse(json), function(z) {
  return z.vid
})

var result = _.pairs(grouped).map(function(item) {
  return { vid: item[0], san: _.pluck(item[1], 'san') }
})