SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict skunkbad's Avatar
    Join Date
    Apr 2008
    Location
    Temecula, CA
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dynamic object key?

    I'm not sure if I'm calling it the right thing, but I'm trying to dynamically create a bunch of key => value pairs in a javascript object.

    Something like this:
    Code JavaScript:
    var pets = {};
     
    for( var i=1; i<=4; i++ ){
    	pets = $.extend( pets, {
    		'pet-type-' + i:		$('#pet-type-' + i).val(),
    		'pet-breed-' + i:		$('#pet-breed-' + i).val(),
    		'pet-age-' + i:		$('#pet-age-' + i).val(),
    		'pet-weight-' + i:	$('#pet-weight-' + i).val(),
    		'pet-comments-' + i:	$('#pet-comments-' + i).val()
    	});
    }

    or this:

    Code JavaScript:
    var people = {};
     
    for( var i=1; i<=10; i++ ){
    	people = $.extend( people, {
    		i + '-first-name':		$('#first-name-' + i).val(),
    		i + '-last-name':			$('#last-name-' + i).val(),
    		i + '-dob':				$('#date-of-birth-' + i).val()
    	});
    }

    But the console gives me errors, and I haven't been able to find a way to do this. I've tryed putting the keys in square brackets, as was suggested somewhere online, but that didn't work.

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Using the jQuery extend method wouldn't be the best nor the easiest way to do this as currently the code would just overwrite the object with each pass, see the below link for an easy way to do this.

    Edit this Fiddle - jsFiddle - Online Editor for the Web (JavaScript, MooTools, jQuery, Prototype, YUI, Glow and Dojo, HTML, CSS)

  3. #3
    SitePoint Addict skunkbad's Avatar
    Join Date
    Apr 2008
    Location
    Temecula, CA
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That obviously works, but this object becomes the data for an ajax post, and turning the post keys into arrays just makes for more work when validating the data in php (at least for me). I ended up getting rid of the jQuery $.extend usage and just populated the object in a for loop with something like this:

    Code JavaScript:
    var pets = {};
     
    for( var i=1; i <= 4; i++ ){
         pets['type-' + i] = $('#pet-type-' + i).val();
         pets['breed-' + i] = $('#pet-breed-' + i).val();
         // etc....
    }
     
    $('#client_data').data(pets);

    Probably not the most elegant solution, but it gets me from point A to point B, and I spent way too long getting to point B! Thanks for your time.


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
  •