0

I have some arrays and I want to insert dynamic multidimension array

var multi = [];
var group = 'fruit';
var fruit_name = 'apple';
multi[group][fruit_name].push({'berbiji' : 'ya', 'panen' : '3tahun'});

why error like this "TypeError: multi[group] is undefined"

Abk
2,2431 gold badge25 silver badges34 bronze badges
asked Nov 18, 2016 at 6:39
2
  • 1
    index can only integer in array Commented Nov 18, 2016 at 6:41
  • Well that's a hash and not array. Commented Nov 18, 2016 at 6:42

2 Answers 2

4

You are trying to make array act like an object. If you want to make your code work, than you should write like:

var multi = {};
var group = 'fruit';
var fruit_name = 'apple';
multi[group] = {};
multi[group][fruit_name] = [];
multi[group][fruit_name].push({'berbiji' : 'ya', 'panen' : '3tahun'});
answered Nov 18, 2016 at 6:43
Sign up to request clarification or add additional context in comments.

1 Comment

yes it is oonly example for my javascript project, iam adversity to solve this problem, and it's working!! thanks!
0

The names of the keys ('fruit' and 'apple') are not numbers so it is not a matrix (array of arrays) but a set of nested objects.

Nested Array (keys are numbers):

multiArray = [[
 {'berbiji' : 'ya', 'panen' : '3tahun'}]]
]]
multiArray[0][0].panen === '3tahun' // true

Nested Object (keys are strings):

multiObject = {
 fruit: {
 apple: {'berbiji' : 'ya', 'panen' : '3tahun'}
 }
}
multiArray[group][fruit_name].panen === '3tahun' // true

Either way, the nested object or array needs to be initiated before you can assign values to keys.

To follow your example:

var multi = {}
var group = 'fruit'
var fruit_name = 'apple';
multi[group] = {} // same as multi.fruit = {}
multi[group][fruit_name] = {'berbiji' : 'ya', 'panen' : '3tahun'}
multi.fruit.apple.panen === '3tahun' // true
answered Nov 18, 2016 at 7:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.