Reputation: 377
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
arr
now looks like this -> [key, Array(1)]
New data comes into barr
how to i push another item into the nested array for the same key?
expected output should be something like this: [key, Array(2)]
Upvotes: 0
Views: 1636
Reputation: 62566
Option #1:
You can push into the barr
array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
barr.push('key2', 'key3');
console.log(arr);
barr
is a reference to the array, and when you pushed it into your arra
array you actually put there the reference, so when updating barr
your reference is still there (and updated).
Option #2:
You can push into the array that is in the 2nd place of your array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
arr[1].push('key2', 'key3');
console.log(arr);
Upvotes: 2
Reputation: 1614
The way you did it the "key" is actually just another value in the array (at index 0). If you want to use a string as the key you'll have to use an object. You can set and get properties using the bracket syntax. The bracket syntax works with arrays as well, but only using integers as keys.
var obj = {};
var barr = [];
var key = "key1";
obj[key] = barr;
// barr changed
obj[key] = barr;
Upvotes: 0