Siki-Siki
Siki-Siki

Reputation: 113

Javascript Multidimension array

I would like to create a multidimensional array. Something like this:

array(
    1234=>array(
        "customInfo1"=>1
        "customInfo2"=>2
    ),
    5678=>array(
        "customInfo1"=>3
        "customInfo2"=>4 
    )
)

I try to do this

var myarray = [];
function headerBuffer(transId,column,value){
    myarray [transId][column] = value;
}

I have to create and update this array. If the input field is updated this function run again and the new record have to insert or update the array.

Upvotes: 0

Views: 68

Answers (3)

Ayush Gupta
Ayush Gupta

Reputation: 9295

PHP's Associative arrays are objects in JS. SO you need to do:

let obj = {
    "1234": {
        "customInfo1": 1,
        "customInfo2": 4
    },
    "5678": {
        "customInfo1": 3,
        "customInfo2": 4
    }
}

Though, object keys in JS can only be strings, so you need to take that into account.

So you need to modify your code as:

var obj = {};
function headerBuffer(transId,column,value){
    // If transId does not exist yet, make it an empty object
    if (!obj[transId] {
        obj[transId] = {};
    }
    obj[transId][column] = value;
}

Upvotes: 1

Pradeep
Pradeep

Reputation: 140

Something like this :

var val1 = '1234'
var val2 = '43456'

var parentArray = [];
var childArray1 = [1,2,3,4];
var childArray2 = [4,3,4,5,6];

parentArray[val1] = childArray1 ;
parentArray[val2] = childArray2 ;

But above solution takes lot of memory.

Better to make parentArray as Map object.

Like this :

var parentMap = new Map();


var val1 = '1234'
var val2 = '43456'

var childArray1 = [1,2,3,4];
var childArray2 = [4,3,4,5,6];

parentMap.set(val1 , childArray1);
parentMap.set(val2 , childArray2);

To get values of parentMap :

parentMap.get(val1);
parentMap.get(val2);

Upvotes: 0

Rafiqul Islam
Rafiqul Islam

Reputation: 961

Try This:

var items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(items[0][0]); // 1
console.log(items);

Upvotes: 0

Related Questions