【发布时间】:2019-06-28 01:10:27
【问题描述】:
我有一个需要迭代的 Map() 对象,因此我可以获得星期几和选定的时间。下面的代码不起作用,因为Object.keys(newFieldReservationPrice).forEach 试图循环一个 Map() 对象,这似乎没有任何意义。那么,有没有更好的解决方案呢?
下面是代码:
handlePriceInput = (e, hour, day) => {
let value = e.target.value
const newFieldReservationPrice = this.state.newFieldReservationPrice
console.log('newFieldReservationPrice', newFieldReservationPrice) // A Map();
let map;
if (!newFieldReservationPrice instanceof Map) {
console.log('!== Map')
console.log('newFieldReservationPrice is a Map()? inside if ()', newFieldReservationPrice)
if (newFieldReservationPrice[day] && newFieldReservationPrice[day][hour]) {
newFieldReservationPrice[day][hour] = Number(value)
}
} else {
map = new Map();
console.log('map object', Object.keys(newFieldReservationPrice)) // logs map object []
Object.keys(newFieldReservationPrice).forEach(key => {
console.log('key', key)
map.set(key, new Map(Object.entries(newFieldReservationPrice[key])));
}); // This doesn't work
console.log('Am I a Map()? map', map)
const aux = map.get(day)
console.log('aux day', aux) // A Map()
aux.set(hour, Number(value)) // Comes as undefined || Cannot read property 'set' of undefined
console.log('aux set', aux) // A Map()
map.set(day, aux);
console.log('what do I have?', map)
}
const isReservationPrice = !newFieldReservationPrice instanceof Map ? newFieldReservationPrice : map
console.log('isReservationPrice', isReservationPrice)
this.setState({
newFieldReservationPrice: isReservationPrice
})
}
谢谢! :)
【问题讨论】:
-
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 提问前先在google上搜索一下
-
可能重复:stackoverflow.com/questions/47135661/…。不完全是骗子,所以虽然不标记为骗子
标签: javascript reactjs