i want create multidimensional array values retrieved on ajax post request.
api response
[{"id":"35","name":"iama","code":"24"},{"id":"23","name":"iamb","code":"08"}]
jquery code
var mularr = []; $.ajax({ type: 'post', url: '/path/to/apiendpoint', datatype: 'json', data: { codes: codes }, success: function(data) { $.each(data, function(key, value) { mularr[key]['id'] = value.code; mularr[key]['text'] = value.name; }); } });
syntax error
typeerror: mularr[key] undefined
i can fetch data
endpoint, error encounter 1 stated above. in perspective, want multidimensional array/object this:
mularr[0]['id'] = '24'; mularr[0]['text'] = 'iama'; mularr[1]['id'] = '08'; mularr[1]['text'] = 'iamb';
or
[object { id="24", text="iama"}, object { id="08", text="iamb"}]
it happens because mularr[0] not object, , mularr[0]['id'] throw error. try this:
var mularr = []; $.ajax({ type: 'post', url: '/path/to/apiendpoint', datatype: 'json', data: { codes: codes }, success: function(data) { $.each(data, function(key, value) { mularr.push({id: parseint(value.code), text: value.name}); // or try if select2 requires id continuous // mularr.push({id: key, text: value.name}); }); } });
Comments
Post a Comment