0

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}]

1
  • 2
    timeDetail.reduce(( time, detail ) => [ ...time, { value: detail.from }, { value: detail.to }], []); Commented Oct 3, 2020 at 11:26

1 Answer 1

1

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

  • do a map of nested arrays [[{value: x}, {value: y}], [...]] and then flatten it
  • reduce it to a single array
  • or simply loop over the original array with forEach() 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ..Nice answer - very well explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.