javascriptarraysflat

Flat an array tree js


Can you help me please to flat this tree? I have tried a few things and it didn't work. I would like to get the fastest way(Algorithm).

const source = [
  {
    item: { id: 1, name: "item name", code: "1d4g4" },
    children: [
      {
        item: { id: 2, name: "item name 2", code: "1d4g4" },
        children: [
          {
            item: { id: 2, name: "item name 2", code: "1d4g4" },
            children: [
              {
                item: { id: 3, name: "item name 2", code: "1d4g4" },
                children: [
                  { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                  { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                  { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
];

This is result that i expect to have:

  { id: 1, name: 'item name', code: '1d4g4' },
  { id: 2, name: 'item name 2', code: '1d4g4' },
  { id: 2, name: 'item name 2', code: '1d4g4' },
  { id: 3, name: 'item name 2', code: '1d4g4' },
  { id: 4, name: 'item name 2', code: '1d4g4' },
  { id: 4, name: 'item name 2', code: '1d4g4' },
  { id: 4, name: 'item name 2', code: '1d4g4' }
]```

Solution

  • After fixing your syntax to be actually valid JavaScript, you'll need a recursive function:

    function flatten(destArray, nodeList) {
      nodeList.forEach((node) => {
        destArray.push(node.item);
        flatten(destArray, node.children || []);
      });
    }
    
    const source = [
      {
        item: { id: 1, name: "item name", code: "1d4g4" },
        children: [
          {
            item: { id: 2, name: "item name 2", code: "1d4g4" },
            children: [
              {
                item: { id: 2, name: "item name 2", code: "1d4g4" },
                children: [
                  {
                    item: { id: 3, name: "item name 2", code: "1d4g4" },
                    children: [
                      { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                      { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                      { item: { id: 4, name: "item name 2", code: "1d4g4" }, children: [] },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ];
    
    const dest = [];
    flatten(dest, source);
    console.log(dest);
    

    outputs

    [
      { id: 1, name: 'item name', code: '1d4g4' },
      { id: 2, name: 'item name 2', code: '1d4g4' },
      { id: 2, name: 'item name 2', code: '1d4g4' },
      { id: 3, name: 'item name 2', code: '1d4g4' },
      { id: 4, name: 'item name 2', code: '1d4g4' },
      { id: 4, name: 'item name 2', code: '1d4g4' },
      { id: 4, name: 'item name 2', code: '1d4g4' }
    ]