SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    3MTA3
    Join Date
    Jul 2003
    Location
    Florida
    Posts
    1,016
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Multidimentional Objects

    Upon researching on a way to transfer a set of data, I read that you should use JavaScript Objects instead of Arrays. However, I can't get the following example to work. Can someone help shed some light on what I'm doing wrong?

    HTML Code:
    <script language="javascript">
    
    var products = new Object();
    
    var products[1] = new Object();
    products[1]['name'] = "Tv";
    products[1]['price'] = "$500.00";
    
    var products[2] = new Object();
    products[2]['name'] = "DVD Player";
    products[2]['price'] = "$130.00";
    
    
    alert(products[2]['price']);
    
    </script>

  2. #2
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    var products = [{name:"Tv1",price:"$500.00"},{name:"Tv2",price:"$400.00"},{name:"Tv3",price:"$300.00"}];
    alert(products[2]['name']);
    alert(products[2]['price']); 
    A property object can't be numeric.

    Bye.

  3. #3
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right - what whisher proposed is a numeric array of "product" objects.
    Another way would be to index it on something like product ID:

    Code:
    var products = {}; // same as new Object();
    
    products["00203121"] = {
       name: "TV", 
       price: "$500.00"
    };
    products["10010010"] = {
       name: "DVD Player",
       price: "$130.00"
    }
    
    alert(products["10010010"].name);

  4. #4
    3MTA3
    Join Date
    Jul 2003
    Location
    Florida
    Posts
    1,016
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks to both of you!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •