1

I got a little lazy and just used PHP to store all these values, I should be using Javascript to do this though. Whats the best way to do the following in Javascript? I would then be using jQuery's .each function to loop through it.

  $accessories = array (
       array('name' => 'Chrome pull out wire Basket 500 & 600 wide ', 'price' => '60'),
       array('name' => 'Chrome shoe rack 2 Tier', 'price' => '95'),
       array('name' => 'Chrome Shoe Rack 3 Tier', 'price' => '145'),
       array('name' => 'Chrome pull out trouser rack', 'price' => '40'),
       array('name' => 'Pull out tie rack', 'price' => '135'),
       array('name' => 'Pull Down hanging Rail 450mm to 1190mm width', 'price' => '33.50'),
       array('name' => 'Corner Hanging Rail', 'price' => '33.50')
        );
0

3 Answers 3

9

JavaScript doesn't have associative arrays, so you'd have to build it as a series of objects in an array.

var accessories = [
    { 'name' : 'Chrome pull out...', 'price' : 60 },
    { 'name' : 'Chrome shoe rack..', 'price' : 95 }
];

You could then cycle over it using $.each as you requested:

$.each( accessories, function(){
    alert( this.name );
});

Fiddle: http://jsfiddle.net/jonathansampson/HXwMc/

Quickly Convert PHP Array to JSON

You can get the above structure easily by passing the array through json_encode():

echo json_encode( $accessories );
Sign up to request clarification or add additional context in comments.

1 Comment

+1, and you (possibly without knowing) corrected the spelling of accessories which the OP should probably do as well.
4

It would probably look like this:

var array = [
    {"name": "Chrome pull out wire Basket 500 & 600 wide ", "price": "60"},
    {"name": "Chrome shoe rack 2 Tier", "price": "95"},
    {"name": "Chrome Shoe Rack 3 Tier", "price": "145"},
    {"name": "Chrome pull out trouser rack", "price": "40"},
    {"name": "Pull out tie rack", "price": "135"},
    {"name": "Pull Down hanging Rail 450mm to 1190mm width", "price": "33.50"},
    {"name": "Corner Hanging Rail", "price": "33.50"}
];

Note that this is an array of objects. JavaScript doesn't have associative arrays, those are objects.

Comments

3

As Jonathan noted, that's an array of objects in Javascript. It would look like this

var accessories = [
  { 
    name: 'hello',
    price: 1.00,
  },
  {
    name: 'world',
    price: 2.50,
  }
]

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.