I'm getting attribute values. I need to set into multidimensional array but it's showing error. where im getting wrong ?
var myArray = [];
amount=10;
x=1
$(id).closest('td').nextAll().find('input').each(function (n) {
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
x++;
});
console.log(myArray);
-
1Possible duplicate of create two dimensional array and loop through it in jqueryJeric Cruz– Jeric Cruz2016年11月02日 07:10:14 +00:00Commented Nov 2, 2016 at 7:10
3 Answers 3
you are missing this line
myArray[x] = {};
before this line
myArray[x]['id'] = $(this).attr('data-id');
since you need to initialize this object first before setting properties to it.
Comments
Arrays need to be declared first to add items. For example
var d = [];
var value = 2;
d[0]["key"] = value;
won't work because d[0] is not an array yet. But:
var d = [];
var value = 2;
d[0]= [];
d[0]["key"] = value;
will work, because d[0] is ready to accept keys.
In your case;
>>> myArray[x] = [];
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
will work.
Comments
Even though, you have initialized the array as an empty array, you should initialize the values at a paritcular location. when you dont specify, myArray[x] is undefined. So, you need to explicitly assign an empty object , so as to update keys using myArray[x]["key"]
var myArray = [];
amount = 10;
x = 1
$(id).closest('td').nextAll().find('input').each(function(n) {
//Need to initialize with an object a location x;
myArray[x] = {};
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
x++;
});
console.log(myArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Comments
Explore related questions
See similar questions with these tags.