1

Yes I know how to loop through arrays (types) in Javascript. The fact is, I'd like to know how to set a multiDimensionalArray array's value by a set of given indexes to keep it as generic as possible. For example I've an array with a length of 3 (which could as well be a length of 4, 100, ...):

var indexes = [0, "title", "value"];

I know the multidimensional array (mArray) can be set by putting the indexes like so:

multiDimensionalArray[0]["title"]["value"] = "Jeroen"; or multiDimensionalArray[indexes[0]][indexes[1]][indexes[2]] = "Jeroen";

The fact that the given indexes array can vary and does not always contain the same index names so I'm search for a solution like this:

multiDimensionalArray[indexes] = "Jeroen";

I don't know how to code the assignation if this. I've searched on Google/Stack Overflow. Maybe I'm using the wrong keywords. Can anyone help me?

Thanks!

2 Answers 2

1

Following example is how I've made it working thanks to Jonas's example:

var json = [{
  "hello": {
    "world": 1,
    "world2": 2
  },
  "bye": {
    "world": 1,
    "world2": 2
  }
}];

var indexes = [0, "hello", "world2"];
var value = "value";

indexes.slice(0,-1).reduce((obj, index) => obj[index], json)[indexes.pop()] = value;
console.log(json);

Sign up to request clarification or add additional context in comments.

Comments

0

So imagine you have a structure like this:

var array=[[["before"]]];

Then you want

var indexes=[0,0,0];
var value="value";

to actually do:

array[0][0][0]="value";

which can be easily achieved with reduce:

indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;

Explanation:

indexes.slice(0,-1) //take all except the last keys and
.reduce((obj,index)=>obj[index] //reduce them to the resulting inner object e.g. [0,0] => ["before"]
,array) //start the reduction with our main array
[indexes.pop()]=value;// set the reduced array key to the value

    var array=[[[0]]];


    var indexes=[0,0,0];
    var value="value";
    indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
    
    console.log(array);

3 Comments

How could this work when using textual indexes like mentioned in the question? I cannot seem to get it working when replacing the zeroes in you example by textual indexes. I'm using textual indexes since the multiDimensionalArray can also contain object data.
It worked by replacing indexes.slice(-1) with indexes.slice(0, -1)
@jeroen oh right, thanks for the info. Im sorry for that obvious mistake... :/

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.