DEV Community

almantas88
almantas88

Posted on

2

How to convert from JSON with references to a JSON tree

How to convert this data:
image

To this data:
image

Top comments (2)

Collapse
 
pepkin88 profile image
Marek Pepke • Edited

Because what you have here is a doubly linked tree, you have a choice how you want to populate the tree. I think it would be easier attaching children to their parents.

What I would do is:

  1. Create a lookup map, to efficiently get a document of a given id
  2. For every document, create an empty array field simply called children (it's because the name childrenID suggest, that it has something to do with ID, not the children themselves)
  3. For every document in the original collection, retrieve the document with the id parentID from the lookup map and push it at the end of the children array
  4. Create an array for result nodes: those documents that have parentID: null. You could use .filter for this.

For better efficiency, you could bundle points 2, 3 and 4 into one.
Good luck!

Collapse
 
almantas88 profile image
almantas88

I FOUND A SOLUTION - jsfiddle.net/cw9rq7ht/6/

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay