用对象内部的项目替换javascript数组

时间:2019-05-27 14:31:28

标签: javascript reactjs

我想显示一些数据,具体取决于月份。我有一个从0到11的数组。我对如何执行此操作感到困惑,因为对象内部有多个数组,这让我感到恐惧

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
];

我有一个可以像这样引用的变量:getMonth(new Date(this.props.startDate))

0

我可以做这样的事情吗?

forEach(data[x].rain[getMonth(new Date(this.props.startDate))])

我想用相应月份的数据替换现有的Rain数组。例如,如果是一月(0),我想要data [1] .rain = 22.4091

如果(getMonth = 0),则预期输出:

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: 22.4091
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: 22.4091
    ],
  },
];

2 个答案:

答案 0 :(得分:2)

您可以使用map()。从map()返回一个对象,该对象的所有属性均与先前相同,但将rain更改为它的第一个元素。

 let arr = [ { l: false, u: 'AU', n: 'Adelaide', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, { l: false, u: 'AU', n: 'A Different Place', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, ];

const res = arr.map(x => ({...x,rain:x.rain[0]}))
console.log(res)

答案 1 :(得分:0)

你可以做到

let data = [ { l: false, u: 'AU', n: 'Adelaide', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, { l: false, u: 'AU', n: 'A Different Place', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, ];

const res = data.map(x => ({...x,rain:x.rain[ (new Date(this.props.startDate).getMonth()) ]}))
console.log(res)

如果已经是日期,则this.props.startDate.getMonth()否则按上述方式转换