Jump to content

Storing data to array based on variable


[dx]

Recommended Posts

Hi,

 

How to store data to array but key based on variable so like:

 

var x = 'key';

data[x] = 'value';

 

If I do console.log(data), I see "x" instead of "key".

 

I need store multidimensional array in format:

 

data

---- key

-------- subkey1

------------ { s1: 'aa', s2: 'bb', s3: 'cc' }

------------ { s4: 'dd', s5: 'ee', s6: 'ff' }

-------- subkey2

------------ { s7: 'gg', s8: 'hh', s9: 'ii' }

------------ { s10: 'jj', s11: 'kk', s12: 'll' }

 

 

Link to comment
Share on other sites

This works...

var data = { key: { subkey1:{ s1: 'aa', s2: 'bb', s3: 'cc',  s4: 'dd',  s5: 'ee',  s6: 'ff' },                     subkey2:{ s7: 'gg', s8: 'hh', s9: 'ii', s10: 'jj', s11: 'kk', s12: 'll' }                   }            };var txt1 = 'subkey1';var txt2 = 's1';document.getElementById('out1').innerHTML = data.key[txt1][txt2];
Edited by davej
Link to comment
Share on other sites

The way you had it should work, but I'd initialize the object first before trying to set properties.

var x = 'key';var data = {}; // Initialize the object first.data[x] = 'value';console.log(data);
Link to comment
Share on other sites

I initialized it above.

 

I need store data like this:

 

var key = some_function_here();

 

data['events'][key] = { event: 'event-name', something: 'else' }

 

So, I'll have multiple arrays for "key".

Link to comment
Share on other sites

Just one more thing.

 

I want append array with new subarray:

 

In PHP it would be like

 

$events[] = array('ddddddd', 'eeeeee');

$events[] = array('fffffffffff', 'gggggggg');

 

But, in JS if I use .push it says that object has no method push.

Link to comment
Share on other sites

creating multidimensional arrays is simple, especially with the shorthand syntax:

var events = [];events.push(['ddddddd','eeeeeee']);events.push(['fffffff','ggggggg']);//another wayvar events = new Array(2);events[0] = [].push('ddddddd','eeeeeee');events[1] = [].push('fffffff','ggggggg');//or just do thisvar events =     [        ['ddddddd', 'eeeeeee'],        ['fffffff', 'ggggggg']    ];

push is an instance method, not a constructor method if you run "Array.push()" its not going to understand what you're talking about. but "(new Array).push()" makes sense to it since you first created an empty array instance and then started to push it. Everything defined in an Array's prototype is an instance method/property which instances will have access to, but the constructor doesn't and vice versa (at least not directly).

Edited by Hadien
Link to comment
Share on other sites

Just one more thing.

 

I want append array with new subarray:

 

In PHP it would be like

 

$events[] = array('ddddddd', 'eeeeee');

$events[] = array('fffffffffff', 'gggggggg');

 

But, in JS if I use .push it says that object has no method push.

 

you should actually show us the code you are using from the beginning, not what works outside of the context of your code.

Link to comment
Share on other sites

creating multidimensional arrays is simple, especially with the shorthand syntax:

var events = [];events.push(['ddddddd','eeeeeee']);events.push(['fffffff','ggggggg']);

 

...Ok, but based on that... what is the proper general on-the-fly form? ...this doesn't work...

var events = [];var inner = [];for (var i=0 ; i<8 ; i++){ for (var j=0 ; j<2 ; j++){   inner[j] = j; } events.push(inner);}
Link to comment
Share on other sites

you're close...

 

when you've created inner, it is an empty array, a length of 0. if you try to add elements via inner[j] = j. you'll most likey add the element, but the Array instance won't properly update itself to reflect it (length likely won't increase, and its possible iterator functions in Array will likely not work). I haven't checked exactly what happens if you do this, but i'm certain it'll give you behavior you don't want, and likely cause array-out-of-bounds errors down the line. you had the right idea about pushing into events.

 

also reinitialize inner inside the outer for loop, or all 8 elements in events will refer to the exact same inner array, which would have 16 elements (if using push).

var events = [];var output = "events[inner[]]:";for (var i=0 ; i<8 ; i++){    var inner = [];// instantiate inside outer loop     for (var j=0 ; j<2 ; j++){         inner.push(j); //or inner[j] = j;    }     events.push(inner);    output+="nt["+i+"]:  [["+inner.join("],  [")+"]]";}console.log(output);/*prints the following:events[inner[]]:     [0]:  [[0],  [1]]     [1]:  [[0],  [1]]     [2]:  [[0],  [1]]     [3]:  [[0],  [1]]     [4]:  [[0],  [1]]     [5]:  [[0],  [1]]     [6]:  [[0],  [1]]     [7]:  [[0],  [1]]*/

the reason my 2nd example,"another way" works is because i first gave events array a preset size of 2 elements (each element initialize to undefined). so events[0] and events[1] are still inbounds of what the Array constructor already allocated for events.

 

EDIT:

bah, I've mixed up languages, inner[j]=j; is valid and safe code. but you do need to reinitialize inner inside the outer loop to get what you want

Edited by Hadien
Link to comment
Share on other sites

Problem was that key is not exists so it throw error.

 

I just made checking if key exists in array, do .push, if not first array[key] = new Array(); and then push.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...