www.webdeveloper.com
Results 1 to 4 of 4

Thread: Retrieving list of names from list of name value pairs

  1. #1
    Join Date
    Sep 2012
    Posts
    1

    Retrieving list of names from list of name value pairs

    I have list of paired values, and i need to get the list of just the first item:

    Example:
    Input: CA: San Francisco, TX:Austin, CA: San Jose, GA: Atlanta, MA: Boston
    Output: CA, TX, CA, GA, MA

    Can someone help me with a Javascript snippet that achieves this? I am thinking on lines of using split and join, but I am getting confused, especially because the number of attributes in the original list is not fixed.

  2. #2
    Join Date
    Mar 2009
    Posts
    452
    <script>
    var Input='CA: San Francisco, TX:Austin, CA: San Jose, GA: Atlanta, MA: Boston';
    var arr=Input.replace(/\s+/g, '').split(',');
    var ext=new Array();
    for (i=0;i<arr.length;i++){
    ext[i]=arr[i].substring(0,2);
    }
    alert(ext.join(','));
    </script>

    hope it works for you

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    "CA: San Francisco, TX:Austin, CA: San Jose, GA: Atlanta, MA: Boston".split(/:[\w\s]+/).join("") // == "CA, TX, CA, GA, MA"

  4. #4
    Join Date
    Jan 2011
    Posts
    117
    obj = {CA:"San Francisco", TX:"Austin", CA:"San Jose", GA:"Atlanta", MA:"Boston"};
    Object.getOwnPropertyNames(obj);
    >> ["GA", "CA", "MA", "TX"]

    p.s.:
    Only IE will preserve the original order, ie:
    ["CA"," TX", "GA", "MA"]

    And you have a problem there with double entry of CA key.
    You'll need to correct that.

    i.e.:
    CA: ["San Francisco", "San Jose"]
    Last edited by Troy III; 09-11-2012 at 10:46 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles