简体   繁体   中英

How to create new array using of existing array?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM