简体   繁体   English

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

[英]Reducer function fails for creating key value pair in reducer object

I call a RSS feed and parse it using a parser. 我调用RSS源,并使用解析器对其进行解析。 I receive an array. 我收到一个数组。 I now want to create an object in the end, that looks like this: 我现在想最后创建一个对象,如下所示:

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

The .reduce function looks like this at the moment. .reduce函数目前看起来像这样。 I receive an error when I try to set the date: 尝试设置日期时收到错误消息:

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;
                }, {});

The error message: TypeError: Cannot set property 'date' of undefined 错误消息: TypeError: Cannot set property 'date' of undefined

The console.log() statement gives me four values that are not undefined, ie the correct and expected values. console.log()语句为我提供了四个未定义的值,即正确和期望的值。

You need to create an object first before you can assign values to it: 您需要先创建一个对象,然后才能为其分配值:

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

The obj = obj || {} obj = obj || {} obj = obj || {} pattern is just shorthand for "create and assign a new object if it doesn't exist yet". obj = obj || {}模式只是“如果尚不存在则创建并分配新对象”的简写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM