gpt4 book ai didi

javascript - Reducer 函数无法在 reducer 对象中创建键值对

转载 作者:行者123 更新时间:2023-11-30 13:59:30 28 4
gpt4 key购买 nike

我调用 RSS 提要并使用解析器对其进行解析。我收到一个数组。我现在想在最后创建一个对象,看起来像这样:

{
"2019-06-13": {
"rates": {
"usd": "1.1289",
"jpy": "122.44",
"gbp": "0.88948",
"chf": "1.1207"
},
"date": "2019-06-13"
}
}

.reduce 函数目前看起来像这样。我在尝试设置日期时收到错误消息:

rateJson = rateArray.reduce((acc, curr) => {
let currObj =
curr['cb:statistics'][0]['cb:exchangeRate'][0];
let currCurrency = currObj['cb:targetCurrency'][0].toLowerCase();
let currDate =
currObj['cb:observationPeriod'][0]['cb:period'][0];
let currRate = {
rate: currObj['cb:observation'][0]['cb:value'][0],
mult: currObj['cb:observation'][0]['cb:unit_mult'][0]
};

console.log(currDate,currCurrency,currRate, acc)


acc[currDate]['date'] = currDate;
acc[currDate]['rates'][currCurrency] = currRate;
return acc;
}, {});

错误信息:TypeError: Cannot set property 'date' of undefined

console.log() 语句给了我四个未定义的值,即正确值和预期值。

最佳答案

您需要先创建一个对象,然后才能为其赋值:

acc[currDate] = acc[currDate] || {};
acc[currDate].date = currDate;
acc[currDate].rates = acc[currDate].rates || {};
acc[currDate].rates[currCurrency] = currRate;

obj = obj || {} 模式只是“创建并分配一个新对象(如果尚不存在)”的简写。

关于javascript - Reducer 函数无法在 reducer 对象中创建键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595544/

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