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"
-
1index can only integer in arrayMahi– Mahi2016年11月18日 06:41:37 +00:00Commented Nov 18, 2016 at 6:41
-
Well that's a hash and not array.Mritunjay– Mritunjay2016年11月18日 06:42:04 +00:00Commented Nov 18, 2016 at 6:42
2 Answers 2
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'});
1 Comment
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
Comments
Explore related questions
See similar questions with these tags.