[英]How to implement the following data structure
I have five different arrays, where the length of each array will be the same.我有五个不同的 arrays,每个数组的长度都相同。 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.
这些对象中的每一个都应具有五个 arrays 中的每一个的内容作为属性。 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.请帮助我如何实现这个结构,谢谢。
What's stopping you from using a for loop?是什么阻止您使用 for 循环?
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.请记住,如果 arrays 的长度不同,这将失败。 It might be wise to guard against that in the for loop.
在 for 循环中防止这种情况可能是明智的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.