2016-11-07 64 views
0

您好我想一个数组从格式转换阵列结构

tableValue= [{typeID:"1",name:"xxxxx"}, 
    {typeID:"1",name:"aaaaa"}, 
    {typeID:"1",name:"bbbbb"}, 
    {typeID:"2",name:"ccccc"}, 
    {typeID:"2",name:"ddddd"}, 
    {typeID:"2",name:"fffff"}, 
    {typeID:"3",name:"ttttt"}, 
    {typeID:"3",name:"yyyyy"}, 
    {typeID:"4",name:"zzzzz"}, 
    {typeID:"4",name:"hhhhh"}] 

转换格式

tableGroup=["fk_type1":[{typeID:"1",name:"xxxxx"},{typeID:"1",name:"aaaaa"},{typeID:"1",name:"bbbbb"}], 
"fk_type2":[{typeID:"2",name:"ccccc"},{typeID:"2",name:"ddddd"},{typeID:"2",name:"fffff"}], 
"fk_type3":[{typeID:"3",name:"ttttt"},{typeID:"3",name:"yyyyy"}], 
"fk_type4":[{typeID:"4",name:"zzzzz"},{typeID:"4",name:"hhhhh"}]] 

更新用 我的成分如下:

createTableValues() { 
    let groups = {}; 
    tableValue.forEach(item => { 
     if (tableGroup[item.typeID]) { 
     tableGroup[item.typeID].push(item); 
     } else { 
     tableGroup[item.typeID] = [{ 'fk_type'+item.typeID }]; 
     } 
    }); 
    } 

在此先感谢

+0

显示我们好远,你都干了些什么:) – L01c

回答

1

你期望的那个不是一个有效的数组。

它应该是这样的,

{"fk_type1":[{typeID:"1",name:"xxxxx"},{typeID:"1",name:"aaaaa"},{typeID:"1",name:"bbbbb"}], 
"fk_type2":[{typeID:"2",name:"ccccc"},{typeID:"2",name:"ddddd"},{typeID:"2",name:"fffff"}], 
"fk_type3":[{typeID:"3",name:"ttttt"},{typeID:"3",name:"yyyyy"}], 
"fk_type4":[{typeID:"4",name:"zzzzz"},{typeID:"4",name:"hhhhh"}]} 

而且代码,

var items = [{typeID:"1",name:"xxxxx"}, 
 
{typeID:"1",name:"aaaaa"}, 
 
{typeID:"1",name:"bbbbb"}, 
 
{typeID:"2",name:"ccccc"}, 
 
{typeID:"2",name:"ddddd"}, 
 
{typeID:"2",name:"fffff"}, 
 
{typeID:"3",name:"ttttt"}, 
 
{typeID:"3",name:"yyyyy"}, 
 
{typeID:"4",name:"zzzzz"}, 
 
{typeID:"4",name:"hhhhh"}]; 
 

 
var output = {}; 
 
var key = 'fk_type'; 
 

 
items.forEach(function(item){ 
 
    var typeID = item.typeID; 
 
    if(!output[key + typeID]) { 
 
    output[key + typeID] = []; 
 
    } 
 
    
 
    output[key + typeID].push(item); 
 
}); 
 

 
console.log(output);

+0

感谢@aruna我问题解决了 – sainu