Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create directory nested JSON object to store value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading