javascript - 如何重命名和删除数组中的多个键?

标签 javascript arrays reactjs charts highcharts

我正在尝试在react js中构建一个饼图,它使用highcharts( https://api.highcharts.com/highcharts/ )只接受以下格式的饼图数据(或者也许我错了):示例 fiddle : https://jsfiddle.net/react_user1/e9cbsrdL/1/

data: [
      {name: 'abc', y: 10},
      {name: 'def', y: 90}
]

我从 API 获取的数据如下所示:

const counts:[
{
"id": "all",
"type": "all",
"count": 1403
},
{
"id": "bad",
"type": "bad",
"count": 0
},
{
"id": "failed",
"category": false,
"type": "failed",
"count": 58
},
{
"id": "changed",
"category": true,
"type": "changed",
"count": 123
}

所以我试图在这里实现三件事:

1. Remove the first {}, with the "id": "all"
2. Rename the key: "id" to name & "count" to y
3. Remove the keys: "type" & "category" & their data

感谢您提供的任何帮助,即使是可以提供帮助的部分答案也将不胜感激。

最佳答案

我认为你可以使用Array.prototype.filter()Array.prototype.map()组合。

使用 filter() 您可以删除不需要的值 - 在您的情况下是 all - 然后使用 map()您可以为数组创建一个新结构。

来自上面提到的文档链接:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

就像这样:

const counts = [
  {
  "id": "all",
  "type": "all",
  "count": 1403
  },
  {
  "id": "bad",
  "type": "bad",
  "count": 0
  },
  {
  "id": "failed",
  "category": false,
  "type": "failed",
  "count": 58
  },
  {
  "id": "changed",
  "category": true,
  "type": "changed",
  "count": 123
  }
];

const result = counts.filter(f => f.id !== 'all')
                     .map(e => ({ name: e.id, y: e.count }));

console.log(result);

希望这会有所帮助!

关于javascript - 如何重命名和删除数组中的多个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578487/

相关文章:

Javascript 访问本地可执行文件

javascript - float div 和滑动动画的奇怪行为

c - 如何只将 12 位写入 C 中的 char 数组?

Java:使用文件读取器在 while 循环中添加到字符串数组

javascript - 使用combineReducers后组件停止更新

javascript - Twitter Bower 文件选择

javascript - 对于类的每个元素,检查内容以查看它是否包含字符串,然后仅更新该元素(如果包含)

php - 通过特定属性的值在数组中搜索对象的最有效方法

javascript - 在 React 中映射异步数据的最佳方式

javascript - 根据源对象是否具有具有特定值的深度嵌套属性,有条件地渲染 JSX 元素