简体   繁体   中英

Javascript - Accessing data from array after converting from csv file

I am importing a csv file into my project which I converted into an array. I am able to get the my data back as an array but I am having a hard time accessing the data inside of it due to how it is structured.

For example, when console.logging my array cardDataList I get a return of:

[…]
​
0: "State"
​
1: "202"
​
3: "129,491"
​

Now with this data I am attempting to append to an HTML id but I am having an issue properly targeting one of the objects. For example, if I'd like to append to an id using 0: "State" I am unable to do cardData[0].0 . I've also tried cardData[0].["name"] but that is returning undefined. My expected outcome is to target each object as it if it were a json object.

For example, if the array was

[...]
Name: "State"

I can access the data by doing cardData[0].Name

Here is my code:

function getCardData() {
    $.ajax({
        type: "get",
        url: cardData,
        async: true,
        success: function (data) {


        let cardDataList = [];
        let csvObjects = $.csv.toObjects(data);

        for (var i = 0; i < csvObjects.length; i++) {
            name = csvObjects[i]["StateName"];
            population = csvObjects[i]["Population"];
            business = csvObjects[i]["Businesses"];

            var arrCardListItem = [
                name,
                population,
                business,];

            cardDataList.push(arrCardListItem);

        }


        const urlStr= window.location.pathname;

        if (urlStr.includes('/state/')) {
            console.log(cardDataList[0])
        }

If you want to access it like an object, then make your cardDataList an array of objects. Consider:

var arr = []
var name = 'test'
var population = 'testpop'

var obj = {
    name, 
    population
}
arr.push(obj)
console.log(arr[0])
console.log(arr[0].name)

result

Object
name: "test"
population: "testpop"
__proto__: Object
test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM