Reputation: 11377
I am new to arrays in jQuery. If I have an array that looks as follows, is there a way that I can access just the numbers (without the item names) ?
I would to extract the group of numbers for each item, so instead of "item1: 5, 7, 9" I would need just "5, 7, 9" etc.
var arr =
{
item1: 5, 7, 9
item2: 3, 5, 3
item3: 1, 7, 5
//...
}
Upvotes: 1
Views: 56
Reputation: 19026
Valid syntax:
var arr =
{
item1: [5, 7, 9],
item2: [3, 5, 3],
item3: [1, 7, 5]
}
Calling arr.item1
will give you back an array: item1
.
Since arr
is an object, you can access its items (keys) like properties.
If you want first number from that array, you can use arr.item1[0]
.
In a more dynamic way, you could use each
:
$.each(arr.item1, function(key, value)
{
console.log('item1 contains number ' + value);
});
Output:
item1 contains number 5
item1 contains number 7
item1 contains number 9
Upvotes: 1
Reputation: 4683
The syntax you are looking for is:
var arr =
{
"item1": [5, 7, 9],
"item2": [3, 5, 3],
"item3": [1, 7, 5]
}
And you can access it with arr["item1"]
and that will return [5,7,9]
.
You could also do it as:
var arr =
[
[5, 7, 9],
[3, 5, 3],
[1, 7, 5]
]
And access it as arr[0]
with a return of [5,7,9]
Upvotes: 1