簡體   English   中英

對象嵌套數組,動態推送

[英]Nested Array of object, push dynamically

我需要更新嵌套的元素列表。

該列表可以有無限數量的嵌套元素,我需要根據級別和位置找到它們以更新數組。

基本上,我正在做一個樹視圖,我需要動態添加節點,因此它可以是動態生成的無限嵌套節點。

我的基本結構是:

const tree = {
  id: 'root',
  name: 'Project: ' + hxr.data.project.name,
  level: 0,
  children: [
    {
      id: 'deliverables',
      name: 'Deliverables',
      children: [
        {
          id: 'd1',
          name: 'Column A',
          children: [
            {
              id: 'c12',
              name: 'config',
              children: [],
              level: 1
            },
            {
              id: 'c123',
              name: 'orthomosaic',
              children: [],
              level: 1
            }
          ],
          level: 1
        },
        {
          id: 'd12',
          name: 'Column B',
          children: [
            {
              id: 'c121',
              name: 'config',
              children: [],
              level: 1
            }
          ],
          level: 1
        }
      ],
      level: 1
    }
  ]
}

請注意,這是一個對象,前兩個級別將始終是靜態的,因此,如果我想更新新元素,我正在做:

tree['children'][0]['children'].push(_node);

我的節點結構在哪里:

const _node = {
  id: uuid(),
  name: node.text,
  children: [],
  level: 1,
  type: node.type ?? 'folder'
}

當我動態添加一個節點並且我想向該節點添加更多元素時,我會遇到困難,因為我丟失了引用。

在我看來應該是這樣的:

1
tree['children'][0]['children'][pos].push(_node);
2
tree['children'][0]['children'][pos]['children'].push(_node);
2
tree['children'][0]['children'][pos]['children'][pos2]['children'].push(_node);

但由於它是動態的,它可能是無限的。 有任何想法嗎?

我能夠以另一種方式解決這個問題。

由於我需要的是向所選節點添加一個子節點,因此我添加了一個 id 參數,然后對數組執行查找深度函數以查找和更新所選節點。

function findDeep(array, id, node) {
        var object;
    
        array.some(function f(a) {
            if (a.id === id) {
                object = a;
                a.children.push(node)
                return true;
            }
            if (Array.isArray(a.children)) {
                return a.children.some(f);
            }
        });
        return object;
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM