【问题标题】:How to create and push values into an 3 dimensional array如何创建值并将其推送到 3 维数组中
【发布时间】:2017-12-22 21:31:53
【问题描述】:

我需要帮助制作一个 3 维数组,我的目标是例如:

仅用于图形说明:-),请参见下面的行

[类别:1[子类别:1[子子类别:1,2],2[子子类别:3,4]]

在上述用户选择的场景中:

category 1
subcategories: 1
subsubcategories: 1,2
subcategories: 2
subsubcategories: 3,4

然后我可以使用这些值创建一个字符串,例如:1^1:1,2^2:3,4

希望有人能理解:)

【问题讨论】:

  • 您在制作 3d 数组时遇到了什么困难?
  • 为什么你想要纯数组而不是创建代表你需要的对象?
  • 我没有反对对象,我只是想以正确的方式收集数据:)

标签: javascript arrays


【解决方案1】:

使用objects 而不是arrays。当您在数组元素上使用字符串索引时,array 会变成object,之后某些数组方法可能无法正常工作。为什么不从一开始就使用object

警告! 如果使用命名索引,JavaScript 会将数组重新定义为标准对象。 之后,一些数组方法和属性会产生不正确的结果。

这取自https://www.w3schools.com

这是一个如何使用它的示例:

// Object = {} instead of array = []
var myObject = {};
myObject['category'] = {1: {subcategories: {1:[1,2], 2: [3,4] }} };


// For example
var anotherObject = {};
anotherObject['category'] = {1: {}, 2: {}};
anotherObject['category'][1] = [1,2];
anotherObject['category'][2] = [3,4];

// Edit: example 3
// ---------------
// result from database JSON format
var resultFromDB = {"category": {"1": {"subcategories": {"1": {"subsubcategories": [1,2]}, "2": {"subsubcategories": [3,4] }}}} };


// example of building new object from input
var myNewObject = {};
var type;

// go through the first level 
for(var index in resultFromDB)
{
  // in case you needed this is how you would check type of input
  type = typeof resultFromDB[index];
  if((type === "object") && (type !== null)) // check if its an object
  {
    // set myNewObject[index] to new object
    myNewObject[index] = {};
    // go through second level
    for(var subIndex in resultFromDB[index])
    {
        // set myNewObject[index][subIndex] as new object
        myNewObject[index][subIndex] = {};
        // go through third level
        for(var subSubIndex in resultFromDB[index][subIndex])
        {
           // simply use an '=' to get all from that level
           myNewObject[index][subIndex][subSubIndex] = resultFromDB[index][subIndex][subSubIndex];
           
        }
    }
  }
}


console.log("This is the new object");
console.log(myNewObject);
console.log("\n");
console.log("This is the original object");
console.log(myNewObject);

// If you need to extract in multiple places you could make a function for quick access
function returnObject(incomingObject)
{
    var myNewObject = {};
    var type;
    
    // ... copy paste here all the above code from example 3 except resultFromDB
    
    return myNewObject;
}

// then just call it from anywhere
var theNewestObject = returnObject(resultFromDB);

【讨论】:

  • 感谢您的回答,您能否举例说明如何使用 push 方法添加这些值?这些值是从数据库中获取的。
  • @ChristerEngholm 我将编辑几个示例,向您展示您可以做什么。
  • 谢谢,我迫不及待想看看:)
  • @ChristerEngholm 好的,我明白了。检查// Example 3 的代码,就是这样。如果您从数据库中输入的结果是JSON 格式(它们应该是),这应该完全适合您。告诉我它是否有效,如果没有发布您的传入(来自数据库)数据,以便我可以确切地看到它的外观,然后我可以调整功能。
猜你喜欢
  • 1970-01-01
  • 2017-12-30
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 2020-12-26
  • 2011-04-11
相关资源
最近更新 更多