0

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.

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

ty the answer. If i get a new "customInfoX", the the previous key and value disappear. So i cant create "customInfo1": 3, and "customInfo2": 4 and so on. Do you have any idea?
obj[transId][column] = value; just do this to add a new customInfo to an existing key
var objassd = {}; function headerBuffer(transId,column,value){ objassd[transId] = {}; objassd[transId][column] = value; } This is now. When the function run again with another "column" its the the previous key("column") and value disappear
I just fixed the answer to only override the column and not the entire transId. Note that you don't loop object the same way as regular arrays.
0

Try This:

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

1 Comment

How should i use this when i want to add a new element or update?
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.