Noob question. Setting array elements throws an error.
I get this error when I run the script: array1[user_id] is undefined.
array1 = new Array();
// the data variable I got from a JSON source
// using jQuery
$.each(data, function(i, item) {
// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;
if (array1[user_id]['user'] != user) {
array1[user_id]['price'] = price;
array1[user_id]['user'] = user;
}
}
asked Jun 11, 2011 at 0:27
Cudos
5,88411 gold badges53 silver badges82 bronze badges
2 Answers 2
First, you should not use an array, if you need a hash map, use objects. In some languages, it's one thing, but in JS they're not.
When defining a nested object you have to define each level as an object.
var hash = {};
// the data variable I got from a JSON source
$.each(data, function(i, item) {
// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;
// Have to define the nested object
if ( !hash[user_id] ) {
hash[user_id] = {};
}
if (hash[user_id]['user'] != user) {
hash[user_id]['price'] = price;
hash[user_id]['user'] = user;
}
}
answered Jun 11, 2011 at 0:38
Ruan Mendes
92.7k31 gold badges162 silver badges225 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Ivan
Who said anything about jQuery?
Jared Farrish
@Ivan - Nobody, but it often times makes life eas(ier).
Ruan Mendes
@Ivan: the poster did, I just modified his original posting so it would work, I didn't add any jQuery. Read before you post and downvote!
Ivan
Ah, you're right. The poster should have mentioned it somewhere since I was thinking of a non-jquery solution.
Ruan Mendes
@Ivan: What was the poster supposed to mention? I also can't stand people that use jQuery for every answer, but the question is clearly not about jQuery, it just uses jQuery as part of the example.
|
If I understand this question correctly, you have to initialize the first dimension of array1 first, like so:
array1[user_id] = {};
then you can do this:
array1[user_id]['user'] = 'whatever';
That is of course assuming your user_id is not undefined.
answered Jun 11, 2011 at 0:33
pixelfreak
17.9k12 gold badges92 silver badges110 bronze badges
2 Comments
Cudos
Problem is that I don't know what the "user_id" variable is before I loop through the "data" variable.
Jared Farrish
Then I would use an object and
try catch.lang-js
array1[user_id] is undefined?