Merging and restructuring nested objects with aggregation

JavaScript Hard objects

Task «Merging and restructuring nested objects with aggregation»

Write a function that takes an array of objects with fields: id (number), parentId (number or null), name (string), and value (number). It is necessary to build a tree where each node contains fields id, name, value (the sum of the values of all child nodes and its own), children (an array of child nodes sorted by name in alphabetical order). The root is considered the node with parentId = null. If parentId is not found, the object is ignored. If multiple objects have the same id, keep only the first one. Output the resulting tree as a JSON string (without spaces). It is guaranteed that there is exactly one root.

Input Format

First line — number N (number of objects). Then N lines, each in the format: id parentId name value (fields separated by a space, name — a string without spaces).

Output Format

One line — JSON representation of the root node of the tree (with nested children).

Examples

Example 1

INPUT
3 10 null A 100 20 10 B 50 30 10 C 30
OUTPUT
{"id":10,"name":"A","value":180,"children":[{"id":20,"name":"B","value":50,"children":[]},{"id":30,"name":"C","value":30,"children":[]}]}
main.js