循环中总是从数组中获取最后一个值

时间:2019-05-08 10:11:02

标签: javascript arrays

我有一个包含1个子数组的数组。从该数组中,我必须将格式设置为:

    '2012-05-08': {
        dots: [{
            key: 'vacation',
            color: 'blue',
            selectedDotColor: 'white'
        }, {
            key: 'massage',
            color: 'red',
            selectedDotColor: 'white'
        }],
        selected: true
    },

因此,我使用了reduce方法,并将所有日期作为键。现在我得到的对象是某个特定的日期,例如: [{…},{…}]

我得到的最终结果是: 2019-05-08:{dots:Array(1)},它仅获取数组中的最后一个对象。

我想要的实际格式是: 2019-05-08:{dots:Array(2)}。 //子数组的长度

我尝试使用reduce,map,forEach,但是它们都返回数组的最后一个值

let temp = responseJson.data.reduce((previousValue, currentValue) => {
          console.log('current val.... ', currentValue);
          let key = moment(currentValue.event_date).format('YYYY-MM-DD');

            previousValue[key] = currentValue.events;


          return previousValue;
        }, {});

温度输出: 2019-04-16:(2)[{…},{…}] ...

eventDates = responseJson.data.map(({ event_date} ) => moment(event_date).format('YYYY-MM-DD'));
// array of date string
if(eventDates.length) {
          let eventRecord;

          eventDates.map((date) => {
            eventRecord = temp[date];
            this.setState({ eventData1 : eventRecord.reduce((previousValue, currentValue) => {
              previousValue[date] = {
                dots: [{
                    key:currentValue._id,
                    color: 'black'
                }]
              }

              return previousValue
            }, {}) }, () => console.log('states... ', this.state.eventData1))

            })
        }

这是响应json:

carerId: "5cad711296b53f1d16b137d0"
event_date: "2019-04-17T12:32:36.131Z"
events: (2) [{…}, {…}]
grandpaId: "5cad8a5cb5b125269edd816b"

1 个答案:

答案 0 :(得分:0)

您正在为reduce处理器中的点分配1个元素。需要分配点的当前值以及新值。使用扩展数组ES6。

where id in (1,2,3)

请不要在地图函数中调用setState

相关问题