简体   繁体   中英

Insert Data into a Array periodically JS(react native)

I have a simple array which contains objects like the following -

Array:{
  o1:{
    }
  o2:{
    }
  o3:{
    }
  ......
  o100:{
    }
}

So here I have an object -

OBJECT:{

  }

Which I need to insert into the array periodically - like after every 5 items the new object should be inserted.

So how should I insert it into the array? The data in the existing index should not be overwritten.

Anyone can give me a hint?

Thanks.

It depends on the use case but it looks like you want to use the splice [javascript array method]. If you have your complete Array object, you can loop over it with something like this:

const step = 5;
for (var i = step; i < yourArrayObject.length; i += step) {
  yourArrayObject.splice(i, 0, objectToInsert)
}

This will take your completed Array object and insert the object every step places. Be aware that this code will mutate the original Array object.

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