suuuustt
suuuustt

Reputation: 85

How to iterate children from array in javascript?

i Have an array that could be :

arr1 = ["node1","children1","children1.1","children1.1.1"]

or it could be

arr2 = ["node1","children1"]

and I want to make it in this json format :

const data_arr1 = [{
      title: "Node 1",
      childNodes: [
        { title: "Childnode 1" ,

          childNodes: [
            {
              title: "Childnode 1.1",
              childNodes: [
                { title: "Childnode 1.1.1" }
              ]
            }
          ]
        }
      ]
    }];

  var data_arr2 = {title:"node1",childNodes:{title:"children1"}}

I have do like that but i can't have the right format in iterative way :

BuildJson = (items) => {
    const elements = items.split(",");

    let result = {};
    var children = []
    result["title"] = elements[0];
     elements.shift()
     if(elements.length>1) {
       for(var i=0;i<elements.length;i++){
         elements.map((el,idx)=> {
           children.push({title:el})
         })
       }
       result["ChildNodes"] = children
     }

Please how can I fix this algorithm ?

Upvotes: 0

Views: 54

Answers (2)

Pablo CG
Pablo CG

Reputation: 816

const arr1 = ["node1","children1","children1.1","children1.1.1"]

const createArray = (arr, i = 0) => {
  const obj = {
	title: arr[i]
  };
  if (i < arr.length - 1) {
	obj.childNodes = createArray(arr, ++i);
  }
    
  return [obj];
}

const newArr = createArray(arr1);
console.log(newArr);

Upvotes: 1

benjamin Rampon
benjamin Rampon

Reputation: 1416

I suggest you to use recursive function.

I made you an example:

const t = ["lvl1", "lvl2", "lvl3"];

const r = (array) => {
  if (array.length === 1) {
    return {
      title: array[0]
    };
  }
  if (array.length > 1) {
    return {
      title: array[0],
      childNode: r(array.slice(1))
    };
  }
};

r(t);

r(t) returned the following JSON:

{
  "title": "lvl1",
  "childNode": {
    "title": "lvl2",
    "childNode": {
      "title": "lvl3"
    }
  }
}

Upvotes: 1

Related Questions