JavaScript How to process JSON tree?

I've got a tree like:

{
  "nodes": [
    {
      "id":1,
      "children":[
        {
          "id":3,
          "children":[
            {"id":4, "children":[]},
            {"id":5, "children":[{"id":6, "children":[]}]}
          ]
        },
        {"id":2, "children":[]}
      ]
    }
  ]
}

How to parse this tree to push each node inside children into one new array? I guess I need to parse it recursively. Can you help please?

The output should be like :

let array = [
  {"id":1},
  {"id":2},
  {"id":3},
  {"id":4},
  {"id":5},
  {"id":6},
]
Answer:1

You could take an iterative and recursive approach. I you like to get an ordered result, you could add a sorting.

function getValues(array) {
    return array.reduce((r, { id, children }) => [...r, { id }, ...getValues(children)], []);
}

var data = { nodes: [{ id: 1, children: [{ id: 3, children: [{ id: 4, children: [] }, { id: 5, children: [{ id: 6, children: [] }] }] }, { id: 2, children: [] }] }] };

console.log(getValues(data.nodes));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer:2

You could create your own parse function using reduce method to return all child nodes in flat array structure.

const tree = {"nodes":[{"id":1,"children":[{"id":3,"children":[{"id":4,"children":[]},{"id":5,"children":[{"id":6,"children":[]}]}]},{"id":2,"children":[]}]}]}

function parse(arr) {
  return arr.reduce((r, e) => {
    const {children, ...rest} = e;
    r.push(rest)

    const childNodes = parse(children);
    if (childNodes.length) r.push(...childNodes);

    return r;
  }, [])
}

const data = parse(tree.nodes);
console.log(data)
Answer:3

You can use a recursive function like below:

var nodeObject = {
  "nodes": [{
    "id": 1,
    "children": [{
        "id": 3,
        "children": [{
            "id": 4,
            "children": []
          },
          {
            "id": 5,
            "children": [{
              "id": 6,
              "children": []
            }]
          }
        ]
      },
      {
        "id": 2,
        "children": []
      }
    ]
  }]
}

var ids = [];

function getIds(node) {
  ids.push({
    id: node.id
  });
  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => getIds(childNode))
  }
}
nodeObject.nodes.forEach(node => getIds(node))
console.log(ids);
Answer:4

There are many ways doing this, one of them is my solution. I am sure, you will find better way - but i found Object.entries technique pretty easy.

const myObj = {
  "nodes": [
    {
      "id":1,
      "children":[
        {
          "id":3,
          "children":[
            {"id":4, "children":[]},
            {"id":5, "children":[{"id":6, "children":[]}]}
          ]
        },
        {"id":2, "children":[]}
      ]
    }
  ]
}

let noteArray = Object.entries(myObj.nodes);
let pushArray = [];

for(const [noteKey, noteValue] of noteArray) {
  pushArray.push({"id": noteValue.id});
  
  for(const [childKey, childValue] of Object.entries(noteValue.children)) {
    pushArray.push({"id": childValue.id});
    
    for(const [child2Key, child2Value] of Object.entries(childValue.children)) {
      pushArray.push({"id": child2Value.id});
    }
  }
}

console.log(pushArray);
Answer:5

A recursive solution is the way to go:

const data = {"nodes":[{"id":1,"children":[{"id":3,"children":[{"id":4,"children":[]},{"id":5,"children":[{"id":6,"children":[]}]}]},{"id":2,"children":[]}]}]};

const getChildren = obj => {
  let result = [];
  obj.children.forEach(child => {
    if (child.children && child.children.length) {
      result.push({ id: child.id });
      result = result.concat(getChildren(child));
    } else {
      result.push({ id: child.id });
    }
  });
  return result;
};

let res = data.nodes.flatMap(getChildren);

console.log(res);
snip-css
Answer:6

You can use a function to iterate object by property like below

var object = {
  "nodes": [
    {
      "id":1,
      "children":[
        {
          "id":3,
          "children":[
            {"id":4, "children":[]},
            {"id":5, "children":[{"id":6, "children":[]}]}
          ]
        },
        {"id":2, "children":[]}
      ]
    }
  ]
}

var result = [];
function iterate(obj, stack) {
        
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    //console.log(property + "   " + obj[property]);
                    result.push({[property]: obj[property]});
                    //$('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
        
    }
    
iterate(object, 'id');
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
Answer:7

A basic recursive solution would be:

var tree = {
  "nodes": [
    {
      "id":1,
      "children":[
        {
          "id":3,
          "children":[
            {"id":4, "children":[]},
            {"id":5, "children":[{"id":6, "children":[]}]}
          ]
        },
        {"id":2, "children":[]}
      ]
    }
  ]
}

function parse(tree, current) {
    if (current === undefined || current === null) {
        current = [];
    }
    if (Array.isArray(tree)) {
        tree.forEach(function (node) {
            if (node.id !== undefined) {
              current = current.concat([{ id: node.id }]);
            }
            if (node.children !== undefined) {
               current = parse(node.children, current);
             }
        });
    }
   
    return current;
}      

console.log(parse(tree.nodes));
Answer:8

Please see this minimum example https://codepen.io/rockmandash/pen/Rzwowd The code is this: <div class="cool"> <input type="checkbox" value="checkbox1"> <input type="checkbox" ...

Please see this minimum example https://codepen.io/rockmandash/pen/Rzwowd The code is this: <div class="cool"> <input type="checkbox" value="checkbox1"> <input type="checkbox" ...

  1. check event target class
  2. check event target type
  3. check event target javascript
  4. check event target is input
  5. check event target has class
  6. check event target
  7. check event target id
  8. check event target jquery
  9. check if event target is input
  10. check if event target is element
  11. check if event target has class
  12. check if event target is child
  13. javascript check event target type
  14. check if event target contains class
  15. check if event target is button
  16. react check event target
  17. check if event target is checkbox
  18. js check event target tag
  19. js check event target
  20. check if event target has id

I'm working on a form to add members to a project. Only members whose profiles are recorded in the system can be added. There are a name input field and a position select box. The position select box ...

I'm working on a form to add members to a project. Only members whose profiles are recorded in the system can be added. There are a name input field and a position select box. The position select box ...

  1. jquery autocomplete response example
  2. jquery autocomplete response format
  3. jquery autocomplete response function
  4. jquery autocomplete response map data
  5. jquery autocomplete response
  6. jquery autocomplete response data
  7. jquery autocomplete response not firing
  8. jquery autocomplete response label value
  9. jquery autocomplete response is not a function
  10. jquery autocomplete response event
  11. jquery autocomplete response object
  12. jquery autocomplete response callback
  13. jquery autocomplete response map
  14. jquery autocomplete response is not defined
  15. jquery autocomplete response method
  16. autocomplete jquery response json
  17. autocomplete jquery response return
  18. autocomplete response jquery
  19. jquery ui autocomplete response
  20. jquery autocomplete ajax response

I am developing a website in HTML using bootstrap and javascript. I am trying to add a toast using the following code from the bootstrap website: <div class="toast" role="alert" aria-live="...

I am developing a website in HTML using bootstrap and javascript. I am trying to add a toast using the following code from the bootstrap website: <div class="toast" role="alert" aria-live="...

  1. bootstrap toast does not work
  2. bootstrap toast is not a function

I don't know why this code won't work. I need a simple solution. This is just a college project and it doesn't have to do more then just following: I want to make ti so that when someone enters their ...

I don't know why this code won't work. I need a simple solution. This is just a college project and it doesn't have to do more then just following: I want to make ti so that when someone enters their ...