Reputation: 1375
I have an array that has from
and to
.
I want to create a new array, each of which is a separate object.
For example: I have timeDetail and I want create time
var timeDetail=[{from:12:00:00 ,to:13:00:00}{from:11:00:00 ,to:10:00:00}{from:01:00:00 ,to:02:00:00}]
var time=[{value:12:00:00}{value:13:00:00}{value:11:00:00}{value:10:00:00}{value:01:00:00}{value:02:00:00}]
I did that
this.state.timeDetail.map((i)=>{
var a=i.from;
var b =i.to;
var time=[];
time.push({ Id: time.length+1, Value: a });
time.push({ Id: time.length+1, Value: b });
this.setState({
time :time
})
})
But only the last value is replaced time=[{Id:1,value:01:00:00}{Id :2,value:02:00:00}]
Upvotes: 0
Views: 56
Reputation: 7089
There are mulltiple ways to approach your problem, but map
is only capable of returning an element of element. You have no way of returning 2 elements per 1 looped map parameter.
So you can either
[[{value: x}, {value: y}], [...]]
and then flatten itreduce
it to a single arrayforEach()
and push the individual elements.The simplest out of the 3 is the last mentioned forEach
loop:
someMethod = () => {
const { timeDetail } = this.state
const time = []
timeDetail.forEach(({ from, to }) => {
time.push({ value: from })
time.push({ value: to })
})
this.setState({ timeDetail: time })
}
Next important thing to note - look how I moved the setState()
outside of the forEach
loop, which is something you should always strive to do.
That's also the reason why your state got update only once. The setState()
method is asynchronous and does not mutate the state directly, instead it creates a pending state transition. To put it in simpler terms - never put setState()
inside a loop, instead mutate the array first and then set the mutated array as the new state.
Outside of the buggy behaviour, even if it worked, your application would be much less performant because of updating state on every loop iteration.
Upvotes: 1