-3

I have five different arrays, where the length of each array will be the same. I want to create a new array of objects where no of objects is equal to the length of array mentioned earlier. Each of those objects should have the contents of each of the five arrays in order as properties. Like this

const arrId = [id1, id2, id3];
const arrUserName = [userName1, userName2, userName3];
const arrUserImg = [userImg1, userImg2, userImg3];
const arrText = [text1, text2, text3];
const arrTime = [time1, time2, time3];

I need to create an array like this:

const arr = [
  {
    id1,
    userName1,
    userImg1,
    text1,
    time1,
  },
  {
    id2,
    userName2,
    userImg2,
    text2,
    time2,
  },
  {
    id3,
    userName3,
    userImg3,
    text3,
    time3,
  },
];

Please help me on how to implement this structure, Thank You.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Nawaz Mohamed
  • 145
  • 10
  • I *knew* there was a dupe for this somewhere! You're looking for an array op sometimes known as "zip": [Javascript equivalent of Python's zip function](https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – zcoop98 May 28 '21 at 18:12

1 Answers1

0

What's stopping you from using a for loop?

const arrId = [id1, id2, id3];
const arrUserName = [userName1, userName2, userName3];
const arrUserImg = [userImg1, userImg2, userImg3];
const arrText = [text1, text2, text3];
const arrTime = [time1, time2, time3];

let newOjbects = []
for (let i = 0; i  < arrId.length; i++) {
  newObjects.push({
    id: arrId[i],
    userName : arrUserName [i],
    userImg: arrAserImg[i],
    text: arrText[i],
    time: arrTime[i]
  })
}

Keep in mind this will fail if the arrays are not all the same length. It might be wise to guard against that in the for loop.

jrend
  • 784
  • 2
  • 11
  • 30