我怎样才能将这个数组转换成(下面提到的)并在typescript中将另一个子数组转换成它

时间:2017-04-29 15:21:43

标签: angularjs arrays object typescript

[{
     "header": "API",
     "value": "hello"
  },
  {
     "header":"API",
     "value":"yellow"
 },
   {
     "header":"Other",
      "value":"yallow"},
    {
      "header":"other",
      "value":"othertt"
     }

   ]

这是我所拥有的列表,我想通过其标题相同的匹配位于一个对象下并且其他值以数组形式出现,例如在" API"对象的标题是API,并将标题的所有值都放入一个数组中,并将所有与标题匹配的值与" api"制作它们的数组并将它们放入该对象我想要的是一个带有下面数组值的标题是我想要从这个对象数组生成的输出。这怎么可能在打字稿

 [
   {
     "header": "API",
     "data": [
     {
         "value": "hello"
     },
     { 
         "value": "yellow"
      },
     ]

   },

  {
    "header": "other",
    "data": [
    {
         "value": "yallow"
    }
   { 
         "value": "othertt"
   }


   ]}
  ]

1 个答案:

答案 0 :(得分:0)

此代码证明可以在我的测试角应用程序中使用:



const arr = [{
      "header": "API",
      "value": "hello"
    },
    {
      "header":"API",
      "value":"yellow"
    },
    {
      "header":"other",
      "value":"yallow"
    },
    {
      "header":"other",
      "value":"othertt"
    }];
    
    const keys = [];

    for (let i of arr) {
      if (!keys.includes(i.header)) keys.push(i.header);
    }

    const result = keys
      .map(k => Object.assign({ header: k }, { 
        data: arr.filter(x => x.header === k)
        .map(y => Object.assign({}, { value: y.value })) 
      }));

    console.log(JSON.stringify(result, null, 2))