我从本地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函数已经取得了一些进展,但这并不是我想要的。我希望有人可以指出正确的方向
答案 0 :(得分:3)
将对象数组简化为一个对象,并为每个class Base<T>
{
protected T Foo();
}
class Derived : Base<int>
{
public new int Foo() => base.Foo();
}
class AnotherDerived : Base<string>
{
public new string Foo() => base.Foo();
}
创建一个属性,并为每个name
初始化/更新值:
Gap