为什么在array.push中调用Object.create返回一个空对象列表?

时间:2018-09-05 15:07:50

标签: javascript angular6

我需要创建一个对象数组,其属性值基于包含服务器响应的对象数组的存在而动态设置。

这段代码中的流程对我来说似乎是正确的(根据网络上的某些文章),但是我收到的结果是一个n个空对象的数组(均未显示id:null)。

infoForecasts = [];

buildWidget() {
    this.listForecasts.map( (i) => {
        const ser = this.utilitiesService;
        return this.infoForecasts.push(
            Object.create(
                {
                    id: null,
                    time: ser.getCurrTime(ser.getDateTime(i.dt))
                }
            )
        );
    });
}

我还试图:

...

time: Object.values(ser.getCurrTime(ser.getDateTime(i.dt))

但任何更改。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

不应用于循环数组,而应使用forEach()

我建议您使用reduce()这样:

this.listForecasts.reduce(
  (acc, cur) => [
    ...acc,
    {
      id: null,
      time: this.utilitiesService.getCurrTime(
        this.utilitiesService.getDateTime(cur.dt)
      )
    }
  ],
  []
);

但是,如果您只想推动某物,那么Array.push({ id: '', time: '' })应该很好!