0

I asked this question and the question was filtered as a related question regarding asynchronous callback.

I got the idea of asynchronous callback after reading the related post. However, even if I understood the concept, it doesn't solve the problem I have.

Can anyone let me know how to store the data brought from JSON in D3?

My code is

var tableprice=[];


d3.json( "./itemlist.json").then(function(data)
{
    for(let i=0;i<data[0].item[0].table.length;i++){
    tableprice.push(data[0].item[0].table[i].price)}
})

    var update_price=d3.select('body').selectAll('div').data(tableprice);

    update_price.enter().append('div')
    .text(function(d){
        return d})

Outside of the curly braket of d3.json, the array 'tableprice[]' becomes an empty array. I kind of got the concept why it happened, but I don't know how to fix this?

Is there anyway I could keep the array data once the json file was loaded? what I want to do is even if I call the array outside of the curly bracket set (d3.json..), I want to see the array.

Thank you in advance stackoverflow forks!

Soonk
  • 332
  • 2
  • 14

1 Answers1

0

I'm not sure how the rest of your code looks like, but is there are reason why you couldn't do this?:

d3.json( "./itemlist.json")
    .then(data => {
        return data[0].item[0].table.map(item => item.price);
    })
    .then(prices => {
        let update_price = d3.select('body').selectAll('div').data(prices);
        update_price.enter().append('div').text(d => d);
    });

Or even make it shorter:

d3.json( "./itemlist.json")
    .then(data => {
        let prices = data[0].item[0].table.map(item => item.price);
        let update_price = d3.select('body').selectAll('div').data(prices);
        update_price.enter().append('div').text(d => d);
    });

adamk22
  • 581
  • 4
  • 18