Create array within JSON object

Asked

Viewed 1,526 times

0

I am creating an array in JSON, and would like to know how to create another array within the object.

var objeto;
objeto = {
    "item" : [
     {
        "id" : delDiv,
        "nome" : nomeItem.value,
        "cod" : codItem.value
      }
     ]
}

I would like to create a new item with new information without overwriting the already placed information.

2 answers

2


Use the push array to add a new item within this attribute, follow an example:

var novo_item = {
    "id" : delDiv2,
    "nome" : nomeItem2.value,
    "cod" : codItem2.value
};

objeto.item.push(novo_item);

or

objeto.item.push({
    "id" : delDiv2,
    "nome" : nomeItem2.value,
    "cod" : codItem2.value
});

0

Have you tried, for example, that:

       objeto = {
            "item" : [
                {
                    "id" : delDiv,
                    "nome" : nomeItem.value,
                    "cod" : codItem.value
                },
                {
                    "id" : delDiv2,
                    "nome" : nomeItem2.value,
                    "cod" : codItem2.value
                },
                {
                    "id" : delDiv3,
                    "nome" : nomeItem3.value,
                    "cod" : codItem3.value
                }
            ],
            "array2" : [
               //objetos do outro array
            ]
       }

If you want to loop and insert multiple "items" into the array item, you can objeto.item.push(novo_item); where novo_item is the object to be inserted in the array.

  • I thought about it, but this code is inside a Function, and I wanted every time this function was run, to add one more item.

  • 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.