将整个数组的内容推入多维数组的一个索引



我从不同的来源提取不同的信息。这个信息是动态的。我想把它们合并成一个多维数组。在尝试将动态信息推入多维数组时遇到问题之前,我做得很好。

在这一点上,我甚至不知道谷歌什么来找到我需要的解决方案。下面是该代码的一个简化示例。重点是:

  1. 只有帐篷的居住者才会改变
  2. 每个帐篷没有固定的人数。(总会有至少有两个乘员,但没有上限。)

示例代码:

var InformationByTent = [];
var numberOfOccupants;
var Tent01Occupants = ["John", "Sam", "Harry"];
var Tent02Occupants = ["Dawn", "Amy", "Jane"];
var Tent03Occupants = ["Nate", "Peter"];
var arrayOfArrays = [Tent01Occupants, Tent02Occupants, Tent03Occupants];
var totalNumberTents = arrayOfArrays.length;
var CampDuties = ["Build Fire", "Cook Dinner", "Sentry", "Hike Preparation"]
var FridayDuty;
var SaturdayDuty;
var SundayDuty;
for (i = 0; i < totalNumberTents; i++) {
//  Assume there are lines of code here that randomizes the duties and assigns three
//  of those to the FridayDuty, SaturdayDuty, SundayDuty variables. Results:
//  FridayDuty = "Build Fire";
//  SaturdayDuty = "Hike Preparation";
//  SundayDuty = "Cook Dinner";
numberOfOccupants = Tent01Occupants.length;
    InformationByTent.push({
        tentNum: i + 1,
        Friday: FridayDuty,
        Saturday: SaturdayDuty,
        Sunday: SundayDuty,
            }); 
    }

需要的最终结果:

InformationByTent = [
{tentNum:1,Occupant01:"John",Occupant02:"Sam",Occupant03:"Harry",Friday:"Build Fire",Saturday:"Hike Preparation",Sunday:"Cook Dinner"},
{tentNum:2,Occupant01:"Dawn",Occupant02:"Amy",Occupant03:"Jane",Friday:"Hike Preparation",Saturday:"Sentry",Sunday:"Build Fire"},
{tentNum:3,Occupant01:"Nate",Occupant02:"Peter",Friday:"Cook Dinner",Saturday:"Cook Dinner",Sunday:"Sentry"},]

我不知道如何定义标识符或编写语法/方法来推这个:

Occupant01:tent01Occupants[0],
Occupant02:tent01Occupants[1],
Occupant03:tent01Occupants[2]

. .当我不知道每个数组中有多少个元素时。任何提示都会很有帮助!

怎么做:

var info;
for (i = 0; i < totalNumberTents; i++) {
//  Assume there are lines of code here that randomizes the duties and assigns three
//  of those to the FridayDuty, SaturdayDuty, SundayDuty variables. Results:
//  FridayDuty = "Build Fire";
//  SaturdayDuty = "Hike Preparation";
//  SundayDuty = "Cook Dinner";
numberOfOccupants = Tent01Occupants.length;
    info = {
        tentNum: i + 1,
        Friday: FridayDuty,
        Saturday: SaturdayDuty,
        Sunday: SundayDuty,
     };
     for (var x = 0; x < Tent01Occupants.length; x++) {
       info["Occupant" + (x + 1)] = Tent010Occupants[x];
     }
     // And repeat the same for other variables
    InformationByTent.push(info); 
    }

相关内容

  • 没有找到相关文章

最新更新