如何将数组展平或旋转到单个对象?

时间:2013-11-25 17:57:21

标签: javascript arrays multidimensional-array underscore.js array-merge

我想要将几个数组展平为单个对象。任何人都可以看到一种很好的方法来映射或转动数据:

Something: [
  {"Test":0,"Count":206,"Abc":0},
  {"Test":2,"Count":119,"Abc":3},
  {"Test":1,"Count":207,"Abc":3},
  {"Test":3,"Count":129,"Abc":8,
  {"Test":4,"Count":122,"Abc":2}
]

到此?

{
  Name: "Something",
  Test0: 206,
  Test1: 207,
  Test2: 119,
  Test3: 129,
  Test4: 122
}

2 个答案:

答案 0 :(得分:1)

var newSomething = {};
newSomething.name = 'Something';
for (var i=0,l=Something.length;i<l;i++) {
  newSomething['Test'+Something[i].Test] = Something[i].Count;
}

答案 1 :(得分:1)

Array.prototype.flattenOn=function(out,key,value)
{
    for(var i=0,l=this.length;i<l;i++)
    {
        out[key+''+this[i][key]]=this[i][value];
    }
    return out;
};

var obj={
  Something:[
  {"Test":0,"Count":206,"Abc":0},
  {"Test":2,"Count":119,"Abc":3},
  {"Test":1,"Count":207,"Abc":3},
  {"Test":3,"Count":129,"Abc":8},
  {"Test":4,"Count":122,"Abc":2}
  ]
};

var output={};
output.Name='Something';
output=obj.Something.flattenOn(output,'Test','Count');
alert(JSON.stringify(output));

以下是小提琴http://jsfiddle.net/67aXK/