如何使用打字稿

时间:2019-07-03 05:58:48

标签: javascript typescript

我以键值形式的对象数组形式获取数据。如下所示:

"data": [
    {
      "groupBy": "InvalidAuth",
      "count": 41
    },
    {
      "groupBy": "InvalidAuthEmpty",
      "count": 75
    },
    {
      "groupBy": "InvalidAuthSQL",
      "count": 75
    },
    {
      "groupBy": "Unsecured",
      "count": 75
    }
  ]

但是我这里的想法是更改其原始形式并使其如下所示,这意味着键“ count”应为“ value”,键“ groupBy”应为“ name”。如何使用打字稿或javascript以编程方式更改它:

data:[
            {value:41, name:'InvalidAuth'},
            {value:75, name:'InvalidAuthEmpty'},
            {value:75, name:'InvalidAuthSQL'},
            {value:75, name:'Unsecured'}
]

由于原始表格不适用于电子图表。电子图表仅适用于值和名称形式。

有人可以帮助我吗?

谢谢。

4 个答案:

答案 0 :(得分:2)

您可以简单地使用mapdestructuring

const data = [{"groupBy": "InvalidAuth","count": 41},{"groupBy": "InvalidAuthEmpty","count": 75},{"groupBy": "InvalidAuthSQL","count": 75},{"groupBy": "Unsecured","count": 75}]
  
let op = data.map(({count:value,groupBy:name}) => ({name,value}))

console.log(op)

答案 1 :(得分:1)

您可以使用map获取具有所需属性名称的原始数组的副本:

const data = [
    {
      "groupBy": "InvalidAuth",
      "count": 41
    },
    {
      "groupBy": "InvalidAuthEmpty",
      "count": 75
    },
    {
      "groupBy": "InvalidAuthSQL",
      "count": 75
    },
    {
      "groupBy": "Unsecured",
      "count": 75
    }
  ];
  
  const data2 = data.map(x => ({
    value: x.count,
    name: x.groupBy
  }));
  
  console.log(data2);

答案 2 :(得分:0)

也许这可以解决您的问题:

let newData = [];
for(let thisData of data){
  newData.push({
    value: thisData.count,
    name: thisData.groupBy,
  })
}

答案 3 :(得分:0)

您只需要遍历data array并重命名现有密钥并删除较旧的密钥。

var data= [
    {
      "groupBy": "InvalidAuth",
      "count": 41
    },
    {
      "groupBy": "InvalidAuthEmpty",
      "count": 75
    },
    {
      "groupBy": "InvalidAuthSQL",
      "count": 75
    },
    {
      "groupBy": "Unsecured",
      "count": 75
    }
  ]
  
   data.forEach(function(elem){
    elem.name =elem.groupBy;
    elem.value =elem.count;
    delete elem['groupBy'];
    delete elem['count'];
  });
  console.log(data);