2

I have an existing Javascript Array with Keys, like:

var myArray = new Array();
myArray.push({ "id":"A123", "pwd":"helloworld", "items":[] });

So the ..

myArray["items"] <-------- will store multi-dimension Arrays inside again.

.. is currently a blank room.
Then now, how do I add new multiple Arrays into this myArray["items] room?

Lets say I have a loop to add items (total count is dynamic then):

foreach(.......)
{
    var newItem = [{"itemcode": "i1001", "itemname": "apple"}];
    myArray.items.push( newItem ); // NOT WORKING
    myArray["items"] = newItem; // NOT WORKING ALSO
}

Simply debug like this:

alert( JSON.stringify( myArray ) );

.. and it is returning the Array Structure but the "items" room is blank.

So how do I dynamically add new Objects into an existing Array room, with KEY, please?

1 Answer 1

5

The problem is myArray is an array, and the object which has items array is at index 0 so

myArray[0].items.push( newItem );

In your case there is no need to use an array, just use a object lik

var obj = {
    "id": "A123",
    "pwd": "helloworld",
    "items": []
};
obj.items.push(obj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.