Search code examples
javascriptjavascript-objects

How can I add the data of one JS object to another


In the function there is an empty JS object

var globalDataObject = [{}]; 

Then, there is a loop that goes over an array of users, stores the properties of each user in variables (ex. name, lastName, ...) and creates an object for each user:

//create an object containing the current name 
const currentObject = {
    'profile': {
        'name': nameVariable,
        'lastName': lastNameVariable
    }
};

What is the right way to add the data of currentObject to the globalDataObject once it's created? So that at the end the globalDataObject should be:

var globalDataObject = [
    'profile': {
        'name': 'John',
        'lastName': 'Smith'
    },
    'profile': {
        'name': 'Ann',
        'lastName': 'Lee'
    },
    'profile': {
        'name': 'Dan',
        'lastName': 'Brown'
    }
]; 

Important thing is that globalDataObject must be the JS object of the specified format (not the object containing multiple objects and not the array) since once it's created it is going to be converted into XML.


Solution

  • You can create your global object like an array:

    globalDataObject = []; 
    

    And then just push in it:

    globalDataObject.push(currentObject);