我正在尝试在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/