How should I structure a data tree in javascript so that it can be parsed by the front-end?

Viewed 30

I have a tree data structure where every node is an object and I want to send the entire tree to the front-end. JavaScript doesn't allow objects as keys so I can't implement the solution below

tree= {{}:{{}:{}, {}:{}, ...}, ...} 

How do I achieve this and how do I parse back the tree in the front-end .

1 Answers

To make your data serializable (e.g. as JSON), you should use a different data structure where you don't use objects as Map-keys. Check if you have a unique identifier for each object (maybe an ID property?). If not, create one for each object (use a sequential number). Then encode your tree with these identifiers as object keys. Now you can serialize/deserialize using JSON.

Related