首页 > 解决方案 > 动态访问数组内对象内的数组

问题描述

首先,我对 javascript 比较陌生,所以对我来说放轻松:)

这是我的问题。我需要能够动态导航看起来像这样的多维数组:

Categories:[
     {id:cat1,
      name:cat1,
      childrens:[
           {id:cat1-subcat1,
            name:cat1-subcat1,
            childrens:[
                {id:cat1-subcat1-subcat1,
                 name:cat1-subcat1-subcat1,
                 childrens:[
etc...

想法如下:客户端可以创建类别并在其下嵌套子类别,但也可以将子类别放在子类别中。

所以我可以通过执行以下操作将子类别添加到类别中:

categories[position].children.push(newcat)

现在我的问题是如何对子类别做同样的事情。

categories[position].children[x].children.push(newcat)

获取 x 值并将其存储在新创建的类别中是可能的,我想我可以围绕 1 层子类别工作,但想法是它应该能够根据需要创建尽可能多的嵌套子类别。所以它看起来像:

categories[position].children[x].children[y].children[z].children.push(newcat)

所以我需要一种动态的方式来访问这些地方。不知道怎么做。

我可以通过它们的 id 访问那些嵌套对象吗?就像常规数组中的地图一样。

我将如何访问 cat1-subcat1-subcat1 只知道 id 例如?

我希望它有意义,我当然可以提供更多解释

谢谢, 埃斯特班

标签: javascriptarraysmultidimensional-array

解决方案


好的,我找到了一种方法,所以如果有人有同样的问题,这里是:

buildTreeview3(){
        var catdb=JSON.parse(JSON.stringify(this.$catdb))
        var lvl = 0
        var tempcat={}
        var u
        var i
        var parentid

        // count how many lvls max
        for(i=0;i<catdb.length;i++){
          if (catdb[i].level>lvl){lvl=catdb[i].level}
        }
        console.log('lvl : ',lvl)

        // if only base lvl, no need to build treeview
        if(lvl==0){
          this.categories=this.$catdb
        }
        else{
            for(u=lvl;u>0;u--){
              //for each lvl starting from highest, go through the temp database catdb
              for(i=0;i<catdb.length;i++){
                if(catdb[i].level==u){
                  //When found a categorie from current lvl, found the position of its parent and add it to its child
                  parentid = catdb[i].parentid
                  let parentpos = catdb.map(function (e) {
                      return e.id;
                    }).indexOf(parentid);
                    tempcat=catdb[parentpos]
                    tempcat.children.push(catdb[i])
                    
                     //remove the cat that has been added to childs from the temp db
                     //replace the parent by the parent with child
                      catdb.splice(i,1)
                      catdb.splice(parentpos,1,tempcat)
                      i=0
                }
              }
            }

        }//end of all (else if not just base lvl)
      this.categories=catdb

      },

推荐阅读