简体   繁体   English

如何实现以下数据结构

[英]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.

相关问题 结构将如何从 firebase 获取以下数据结构? - How would the structure be to obtain the following data structure from firebase? 如何使用动态数据实现javascript Map结构? - How implement javascript Map structure with dynamic data ? 如何在 JavaScript 中实现“索引连接”数据结构? - How to implement an "index join" data structure in JavaScript? 如何在javascript中实现deque数据结构? - How to implement deque data structure in javascript? 在React / Redux中,如何按照JSON API结构发布数据 - In React/Redux, how to post data following JSON API structure 数据结构-如何在JavaScript中实现哈希表(包括关联列表)? - data structure - how to implement hash tables (including association lists) in javascript? 如何在以下情况下实现自动完成 - How to implement autocomplete for the following scenario 如何创建以下数据结构的集合并使用socket.io发送? - How can i create the collection of following data structure and send using socket.io? 如何将 JSON 转换为以下结构的数组 - How to Convert JSON to Array following structure below 如何使用rxjs Observables实现以下内容? - How to implement following using rxjs Observables?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM