简体   繁体   中英

Referencing arrays within json file

I've spent a day struggling over this one issue and could definitely use some help here. I know it's a newbie sort of question so thanks for any help!!! I have the following sample data in a file 'bar_chart.json'

{ "array1":
[
    {"name": "Locke", "value": 2},
    {"name": "Reyes", "value": 50},
    {"name": "Ford", "value": 12},
    {"name": "Jarrah", "value": 35},
    {"name": "Shephard", "value": 15},
    {"name": "Kwon", "value": 4}
],
    "array2":
    [
    {"name": "Jason", "value": 5},
    {"name": "Reston", "value": 13},
    {"name": "Travis", "value": 12},
    {"name": "Matt", "value": 7},
    {"name": "Glenn", "value": 22},
    {"name": "Kyoo", "value": 28}
    ]
}

I'm trying to access the data in array1 to build a bar chart with and that's where I'm having difficulty. Below is the part of my code where I'm receiving the error.

d3.json("bar_chart.json", function(error, data) {

    data.forEach(function(d) { //error occurs here 'undefined is not a function'

        d.name= d.name
        d.value = +d.value;

    });
...

I've also tried 'd.array1.name' in place of 'd.name' to no avail. Furthermore, if the data is simplified to where I only have the 1st array without the title, my code works smoothly.

Your json is an object, you can't call forEach on an object, you can only call that on arrays.

you can try data.array1.forEach(...) and data.array2.forEach(...)

or, you can loop through the object with for (var x in data) {...}

Per my comment: done like this-

[{ "array1":
    [
        {"name": "Locke", "value": 2},
        {"name": "Reyes", "value": 50},
        {"name": "Ford", "value": 12},
        {"name": "Jarrah", "value": 35},
        {"name": "Shephard", "value": 15},
        {"name": "Kwon", "value": 4}
    ]
 },
 { "array2":
    [
        {"name": "Jason", "value": 5},
        {"name": "Reston", "value": 13},
        {"name": "Travis", "value": 12},
        {"name": "Matt", "value": 7},
        {"name": "Glenn", "value": 22},
        {"name": "Kyoo", "value": 28}
    ]
}];

The reason this should work is because you are asking forEach which should refer to an array. An object, like you are writing, would be called individually. Like @vic states, with forEach. One for each array.

The way I set your code up is putting your two objects into an array

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