What the right one array/object or a combination

25 views Asked by At

i trie first steps in javascript, so please sorry for my miss-knowing :-)

I want to creat a data-variable to store datas in a kind like this

MYDATA['FIRST_ELEMENT']['ABCKEY1']=VALUE
                       ['ABCKEY2']=VALUE
                       ['ABCKEY2']=VALUE

MYDATA['SECOND_ELEMENT']['ABCKEY1']=VALUE
                        ['ABCKEY2']=VALUE
                        ['ABCKEY2']=VALUE
...

As i read, array in javascript wont work fine with alphanumeric keys, so maybe i should create a object or a combination as array and objects?

Hope, someboby could help me and explain me whats the right way to do this,

thanks a lot.

1

There are 1 answers

3
gavgrif On BEST ANSWER

This could be achieved with a single object or an array of objects. An advantage to using an array of objects is that you can iterate over it and create a list of items or a table structure etc.

// using an object

var MYDATA_OBJ= {
  FIRST_ELEMENT: {
    ABCKEY1: 'value 1.1',
    ABCKEY2: 'value 1.2',
    ABCKEY3: 'value 1.3'
   },
  SECOND_ELEMENT: {
    ABCKEY1: 'value 2.1',
    ABCKEY2: 'value 2.2',
    ABCKEY3: 'value 2.3'
   }
 };


console.log(MYDATA_OBJ.FIRST_ELEMENT.ABCKEY2); // gives value1.2
console.log(MYDATA_OBJ.SECOND_ELEMENT.ABCKEY3); // gives value2.3

// to alter the value of a given element the syntax would be 
MYDATA_OBJ.FIRST_ELEMENT.ABCKEY2 = 'newValue1.2';
console.log(MYDATA_OBJ.FIRST_ELEMENT.ABCKEY2); // gives newValue1.2

// using an array

var MYDATA_ARR= [{
    ABCKEY1: 'value 1.1',
    ABCKEY2: 'value 1.2',
    ABCKEY3: 'value 1.3'
   }, {
    ABCKEY1: 'value 2.1',
    ABCKEY2: 'value 2.2',
    ABCKEY3: 'value 2.3'
   }
 ];


console.log(MYDATA_ARR[0].ABCKEY2); // gives value1.2
console.log(MYDATA_ARR[1].ABCKEY3); // gives value2.3


// to alter the value of a given element the syntax would be 
MYDATA_ARR[0].ABCKEY2 = 'newValue2.2';
console.log(MYDATA_ARR[0].ABCKEY2); // gives newValue2.2