Home > Software design >  How to create directory nested JSON object to store value?
How to create directory nested JSON object to store value?

Time:11-14

How to create directory like structure in JSON that on insertion value is stored inside last JSON object?

example of output :

 let obj = {
     value : 5,
     next : {
       value : 10,
       next : {
          value : 15,
          next : {
             value : 20,
             next : null
                 }
              }
            }
          } 

Now, if we have to insert 25 then it must be stored in the last next node which is after value 20.

CodePudding user response:

If obj has only one value in each level,then below is a reference for you

let obj = {
     value : 5,
     next : {
       value : 10,
       next : {
          value : 15,
          next : {
             value : 20,
             next : null
                 }
              }
            }
          } 

const insert = (value,data) =>{
  let next = data.next
  let prev = null
  while(next!=null){
    prev = next
    next = next.next
  }
  prev.next = {'value':value,next:null}
  return data
}

console.log(insert(22,obj))

  • Related