1

I'm using jQuery CSV to parse a .csv file on my web server. I've got that working using a demo file with a list of countries with additional fields (Common Name, Capital, Country Code, etc.).

From there, I'm using a lookup function found here: Jquery how to find an Object by attribute in an Array to return matching objects from the parsed file.

Here is my code so far:

jQuery(document).ready(function($){                         
    $.ajax({
       type: "GET",
       url: "path/countrylist.csv",
       dataType: "text",
       success: function(data) {
       var data = $.csv.toObjects(data);
       console.log(data);

       var country = lookup(data, "Common Name", "Albania");
       $.each(country, function(i, val) {
           $("#albania").append(i + ": " + val + "<br/>");
       });
     });
  });

This returns the 'Albania' object which I'm displaying in a div with id '#albania':

Sort Order: 2
Common Name: Albania
Formal Name: Republic of Albania
Type: Independent State
Sub Type: 
Sovereignty: 
Capital: Tirana
ISO 4217 Currency Code: ALL
ISO 4217 Currency Name: Lek
ITU-T Telephone Code: 355
ISO 3166-1 2 Letter Code: AL
ISO 3166-1 3 Letter Code: ALB
ISO 3166-1 Number: 8
IANA Country Code TLD: .al

Where I'm stuck is I want to display a subset of this data from the country object. For example, I only want to display the Common Name, Capital and Country Code.

Assuming that these keys/header rows are the same for each country, how can I show just those values? jQuery .slice() is not working, perhaps because this is an object and not an array(?).

Can I select the subset by key/header row name? That could be another option as those won't change.

1 Answer 1

1

This is solved. I needed to use $.each() and dot notation to target specific keys in the object.

Here is my working code that grabs only the Common Name and Capital, then appends that to a div with and id of the country name:

$.each( data, function( i, v ) {
var name = v.Common_Name.toLowerCase();
var country = v.Common_Name;
var capital = v.Capital;

    $("#" + name).append(
        "Name" + ": " + country + "<br/>" 
               + "Capital" + ": " + capital + "<br/>"
    );
});

My html:

<div class="countries clearfix">
    <div id="afghanistan" class="country"></div>
    <div id="albania" class="country"></div>
    <div id="algeria" class="country"></div>
    <div id="andorra" class="country"></div>
</div>

The result:

Name: Afghanistan
Capital: Kabul

Name: Albania
Capital: Tirana

Name: Algeria
Capital: Algiers

Name: Andorra
Capital: Andorra la Vella
Sign up to request clarification or add additional context in comments.

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.