转换数组结构

时间:2016-11-07 09:00:20

标签: arrays json

您好我想从格式

转换数组
 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 }];
      }
    });
  }

提前致谢

1 个答案:

答案 0 :(得分:1)

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

应该是这样的,

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

代码是,

{{1}}