gpt4 book ai didi

javascript - 使用 es6 创建嵌套对象

转载 作者:行者123 更新时间:2023-11-28 16:55:46 24 4
gpt4 key购买 nike

我正在从本地 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函数已经取得了一些进展,但这并不完全是我想要的。我希望有人能指出我正确的方向

最佳答案

将对象数组简化为一个对象,并为每个name创建一个属性,并初始化/更新每个Gap的值:

const 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}]

const result = data.reduce((r, o) => {
const name = r[o.name] || (r[o.name] = {}) // create an object for the name, or use the existing one
name[o.Gap] = (name[o.Gap] || 0) + o.value; // add/update the Gap value

return r
}, {})

console.log(result)

关于javascript - 使用 es6 创建嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59255768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com