简体   繁体   English

如何将新项目推送到 angular7 中的嵌套数组

[英]How to push a new item to nested array in angular7

I have a nested array ,i want to push new item to nested array.我有一个嵌套数组,我想将新项目推送到嵌套数组。

FoodNode= [
  {
    name: 'Fruit',
    parent:'root',
    children: [
      {name: 'Apple',parent:'Fruit'},
      {name: 'Banana',parent:'Fruit'},
      {name: 'Fruit loops',parent:'Fruit'},
    ]
  }, {
    name: 'Vegetables',
    parent:'root',
    children: [
      {
        name: 'Green',
        parent:'Vegetables',
        children: [

        ]
      }, {
        name: 'Orange',
        parent:'Vegetables',
        children: [         
        ]
      },
    ]
  },
];

Now i want to add it to childrens of green.现在我想将它添加到绿色的孩子。

   this.fileElements.filter(res => {
      if (res.parent === 'root') {
        this.fileList.push(res);
      } else {
          this.fileList.filter((search, index) => {
          if (search.name === res.parent) {
            console.log(typeof search.children === 'undefined');
            search.children.push(res);
          }
        });
      }
    });

this code push the item to 1 level only (like immediate children),bases on parent value Im pushing element to the children.I'm using mat-tree so I need same structure.please help此代码仅将项目推送到 1 级(如直接子项),基于父值我将元素推送到子项。我正在使用 mat-tree,所以我需要相同的结构。请帮助

Hope it helps.希望能帮助到你。

this.FoodNode.forEach(e => {
   if (e.name == "Vegetables") {
   let abcd = e.children;
   abcd.forEach(e1 => {
   if (e1.name === "Green") {
      let data = [
          { name: "Apple" },
          { name: "Banana" },
          { name: "Fruit loops" }
      ];
      data.forEach(e2 => {
      e1["children"].push(e2);
    });
   }
});
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM