Search code examples
javascriptarraysobjectnested-object

How can I dynammicaly create an object inside a object, on a array in JavaScript


How do I dynamically create an object inside another object?

I got this code:

var lista = [{
        "product": "Dipers",
        "quantity": 2
    },
    {
        "product": "Beear",
        "quantity": 6
    },
    {
        "product": "Bread",
        "quantity": 10
    }
];

But I need to add new objects so it'll look something like this:

var lista = [{
        "product": "Dipers",
        "quantity": 2

        seller1 = {
        "name": "B&J",
        "adress": "that street"
        }
        seller2 = {
        "name": "B&J",
        "adress": "that street"
        }

    },
    {
        "product": "Beear",
        "quantity": 6
    },
    {
        "product": "Bread",
        "quantity": 10
    }
];

How would I add seller1 and seller2 dynamically to the existing object lista?


Solution

  • Just assign the new object properties that you wrote/retrieved to a new variable and then simply use dot notation to retrieve the new properties and assign it to your object.

    Check and run the following Code Snippet for a practical example of what I described above:

    var lista = [{
            "product": "Dipers",
            "quantity": 2
        },
        {
            "product": "Beear",
            "quantity": 6
        },
        {
            "product": "Bread",
            "quantity": 10
        }
    ];
    
    let newObj = {
      "seller1": {
        "name": "B&J",
        "adress": "that street"
      },
      "seller2": {
        "name": "B&J",
        "adress": "that street"
      }
    }
    
    lista[0].seller1 = newObj.seller1;
    lista[0].seller2 = newObj.seller2;
    
    console.log(lista);


    N.B. An object property uses the colon : and not the equal sign =.