1

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
    //...
}
3
  • 2
    That's not an array. It's an object. That's also not even valid JavaScript syntax. What exactly do you have? Does arr.item1 work for you? Commented Apr 7, 2014 at 20:14
  • 3
    It would be a valid Javascript syntax if items are arrays: item1: [5, 7, 9] and so on... Commented Apr 7, 2014 at 20:15
  • Thanks. Yes, it looks like Justin's example - sorry, I typed that wrong. Commented Apr 7, 2014 at 20:16

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

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.