Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

604
Views
creating a parent / child json object from a large array of path data in javascript

I have a Javascript array of the form:

var array = [Company_stock_content\\LightRhythmVisuals\\LRV_HD", "Big Media Test\\ArtificiallyAwake\\AA_HD", "Big Media Test\\Company\\TestCards_3840x2160\\TestCards_1920x1080",...]

I need to construct a JSON object of the form:

[
   {
        "data" : "parent",
        "children" : [
            {
                "data" : "child1",            
                "children" : [ ]
            }
        ]
    }
]

so for each top level node in the array it can have multiple children that all have children. for example if we take the array snipper provided, the corresponding JSON object would look as such

[{
    "data": "Company_stock_content",
    "children": [{
        "data": "LightRhythmVisuals",
        "children": [{
            "data": "LRV_HD"
        }]
    }]
}, {
    "data": "Big Media Test",
    "children": [{
        "data": "ArtificiallyAwake",
        "children": [{
            "data": "AA_HD"
        }]
    }, {
        "data": "Company",
        "children": [{
            "data": "TestCards_3840x2160"
        }]
    }]
}]

How can I this structure from the given data bearing in mind the original array can have tens of thousands of entries?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Something like this:

const array = ["Company_stock_content\\LightRhythmVisuals\\LRV_HD", "Big Media Test\\ArtificiallyAwake\\AA_HD", "Big Media Test\\Company\\TestCards_3840x2160\\TestCards_1920x1080"];

const result = array.reduce((acc, item) => {
  item.split('\\').forEach((entry, index, splits) => {
    acc[entry] = acc[entry] || { data: entry, children: [] };
    if (index > 0) {
      if (!acc[splits[index-1]].children.some(child => child.data === entry)) {
        acc[splits[index-1]].children.push(acc[entry]);
      }
    } else {
      if (!acc.children.some(root => root.data === entry)) {
        acc.children.push(acc[entry]);
      }
    }
  });
  return acc;
}, { children: []}).children;

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Here's a way to convert lineages into a hierarchy. A simple guard against cycles is to keep a parent pointer and take a lazy approach when setting parent-child relations (if conflicting relations are described, the last one wins).

Consider the lineages:

["A\\E", "A\\F", "B\\G\\I", "B\\G\\J", "C\\H"]

Describing this tree:

  A     B     C
  |     |     |
E   F   G     H 
        |
       I J

const array = ["A\\E", "A\\F", "B\\G\\I", "B\\G\\J", "C\\H"];
const lineages = array.map(string => string.split("\\"));

let nodes = {}

function createParentChild(parentName, childName) {
  const nodeNamed = name => {
    if (nodes[name]) return nodes[name];
    nodes[name] = { name, children: [], closed: false };
    return nodes[name];
  };
  let parent = nodeNamed(parentName)
  let child = nodeNamed(childName)
  if (child.parent) {
    // if this child already has a parent, we have an ill-formed input
    // fix by undoing the existing parent relation, remove the child from its current parent
    child.parent.children = child.parent.children.filter(c => c.name !== childName);
  }
  child.parent = parent
  if (!parent.children.includes(child))
    parent.children.push(child);
}

lineages.forEach(lineage => {
   for (i=0; i<lineage.length-1; i++) {
     createParentChild(lineage[i], lineage[i+1]);
   }
 })

 let roots = Object.values(nodes).filter(node => !node.parent)
 Object.values(nodes).forEach(node => delete node.parent)
 
 console.log(roots)

This approach also works for the (maybe pathological) input like this

// Here, "F" appears as a descendant of "A" and "B"
["A\\E", "A\\F", "B\\G\\I", "B\\G\\F", "C\\H"]

Last one wins:

  A     B     C
  |     |     |
  E     G     H 
        |
       I F
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!