【发布时间】:2020-04-02 23:07:05
【问题描述】:
我从本地 API 获取了一些数据,但不幸的是,我无法控制接下来会发生什么,我希望我可以在 API 调用后使用函数转换数据。
这是我目前拥有的
transformArray = () => {
const { rawData } = this.state
const obj = Object.fromEntries(
rawData.map(category => [
category,
{
aboveExpectation: rawData[0].value,
atExpectation: rawData[1].value,
belowExpectation: rawData[2].value,
},
console.log('category', category),
]),
)
console.log(obj)
}
Output: [object Object]: {aboveExpectation: 6, atExpectation: 31, belowExpectation: 18}
从 API 返回的原始数据如下所示
data [
{
"name": "Animal care",
"Gap": "Above expectation",
"value": 6
},
{
"name": "Animal care",
"Gap": "At expectation",
"value": 31
},
{
"name": "Animal care",
"Gap": "Below expectation",
"value": 18
},
{
"name": "Calving and calf rearing",
"Gap": "Above expectation",
"value": 8
},
{
"name": "Calving and calf rearing",
"Gap": "At expectation",
"value": 29
},
{
"name": "Calving and calf rearing",
"Gap": "Below expectation",
"value": 18
},
{
"name": "Reproduction",
"Gap": "Above expectation",
"value": 7
},
{
"name": "Reproduction",
"Gap": "At expectation",
"value": 25
},
{
"name": "Reproduction",
"Gap": "Below expectation",
"value": 23
}
]
所以我想要一些更可迭代的东西,而不是有 9 个单独的对象,就像这样
"Animals": {
"animalCare": {
"atExpectation": 1,
"aboveExpectation": 13,
"belowExpectation": 15
},
"calvingAndCalfRearing": {
"atExpectation": 1,
"aboveExpectation": 13,
"belowExpectation": 15
},
"Reproduction": {
"atExpectation": 1,
"aboveExpectation": 13,
"belowExpectation": 15
}
},
现在我的 transformArray 函数取得了一些进展,但这并不是我想要的。我希望有人能指出我正确的方向
【问题讨论】:
-
您收到的原始数据是
Array吗? -
是的,它是一个对象数组
-
请使用
console.log(JSON.stringify(result, null, 2))显示数据。从控制台复制和粘贴无法很好地查看对象。 -
copy(JSON.stringify(result, null, 2))在 Chrome 的控制台中会将其直接复制到剪贴板。 -
帖子已更新
标签: javascript json reactjs oop ecmascript-6