2

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);
asked Nov 2, 2016 at 7:03
1

3 Answers 3

2

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.

answered Nov 2, 2016 at 7:06
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Nov 2, 2016 at 7:06

Comments

0

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>

answered Nov 2, 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.