Skip to content
Advertisement

getting confused with trying to insert nesting objects

Currently trying to build a javascript form that converts the inputs into JSON. I’ve managed to create objects that allow multiple keys/values to be entered however I’m struggling to get my head around the logic and code for nesting a child object within an object.

let objects = [];

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btn2').addEventListener('click', function(e) {
        e.preventDefault();

        let infoBoxOne = document.getElementById('key').value // store the key into a variable
        let infoBoxTwo =  document.getElementById('value').value // store the value into a variable

        const lastObject = objects[objects.length-1] // finds the last object in the objects array
        const objectValues = Object.entries(lastObject) // gets all the keys and values 
        const lastKeyValuePair = values[values.length-1]; // stores the last key and value entered into a variable

    })
})

So my initial idea was to find the last key/value within the last object that was added and use something like Object.create() or push() to insert the data. Is there an easier way of achieving this?


edit: here’s a jsfiddle showing what I have exactly so far https://jsfiddle.net/9jrzLxnm/


Secone edit: idea of what I’m trying to achieve

{
  {
    "firstObject":'FirstObject'
  },
  {
    "lastObject": {
      "infoBoxOne": "JlastObject",
      },
  }
}

Advertisement

Answer

Ok firstly you have to set the desired location to place a child object as an object itself.. then the rest is intuitive

My example is on jsfiddle

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btn2').addEventListener('click', function(e) {
        e.preventDefault();

        let childKey = document.getElementById('key').value // store the key into a variable
        let childValue =  document.getElementById('value').value // store the value into a variable

        const lastObject = objects[objects.length-1] // finds the last object in the objects array
        const values = Object.entries(lastObject) // gets all the keys and values 
        const [key,value] = values[values.length-1]; // stores the last key and value entered into a variable
        lastObject[key]={} //turning place to put child into an object
        lastObject[key][childKey]=childValue //placing the nested child
        document.forms[0].reset();
        listToJson();
    })
})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement