I have a multidimensional array that I am creating from a JSON Ajax call to my DB.
With in my Web App, I am trying to dynamically add a new row to the array using javascript along the lines of:
list[new_row_id].item_id = new_value ;
list[new_id].item_title = new_title ;
Clearly I am doing something wrong.
Any guidance would be appreciated.
CodePudding user response:
Adding an element to the end of an array is done with the push-function:
array.push({"item_id": 10101, "item_title": "new title"});
CodePudding user response:
If you meant "new_id" and "new_row_id" to be the same and it differs from an index starting from 0, because the keys are individual database keys, then you can solve it that way:
var any_db_id = 33;
var new_title = 'new title';
list[any_db_id] = {
item_id: any_db_id,
title: new_title
}
That will result in a JSON looking like that:
{
1: {
item_id: 1,
title: 'Entry coming from database 1'
},
5: {
item_id: 5,
title: 'Entry coming from database 2'
},
33: {
item_id: 33,
title: 'new title'
}
}
If the new_id and new_row_id are still same but it is actually just an index (each item has 0, 1, 2 and so on as key), then you should use the solution of Virendra Katariya.
