Browse JSON for graph construction Waterfall D3

Asked

Viewed 39 times

0

I need to build a chart on Waterfall and I’m having trouble walking the JSON to build this chart.

data =  {
"key": "Margem bruta",
"total": 30000,
"value": [
  {
    "name": "Gastos com pessoal",
    "value": -3700
  },
  {
    "name": "Outros rendimentos e gastos",
    "value": -1800
  },
  {
    "key": "Lucro de vendas",
    "total": 25100,
    "value": [
      {
        "name": "Gastos de depreciação e amortização",
        "value": -13400
      }
    ]
  },
  {
    "key": "Lucro com serviços",
    "total": 11700,
    "value": [
      {
        "name": "Juros suportados",
        "value": -3700
      }
    ]
  },

  {
    "key": "Lucro de ações",
    "total": 7100,
    "value": [
      {
        "name": "Imposto sobre rendimento",
        "value": -3300
      }
    ]
  },
  {
    "key": "Resultado liquido",
    "total": 3800
  }
]}];

each 'key' is necessary to create a parent column and each value has its expense "name" and the value of that expenditure "value". I’m having trouble creating a for that goes through this data structure. using a for, it takes only the first value; and using the function

var keys = data[0].value.map(function(d) { return d.key; });

I have the following return:

[undefined, undefined, "lucro de vendas", "lucro de serviços", "lucro
de ações", "Resultado liquido"]

where the Undefined would be the properties 'value' of primary key and the rest are coming in correctly. from now on, thank you very much.

  • Undefined is pq there is no key property in the first two blocks.

  • Even that part I understood. my difficulty is in how to traverse the entire JSON, so that the chart is mounted as follows: +Gross margin -personal expenses -other income and expenses +sales profit -Depreciation expense +Service profit... and so on

1 answer

0

I was able to solve the problem by going through JSON I used two foreach: one to traverse the first level and the other to traverse the second level, if there is any object.

var data1 = Array();
            data.forEach(function (parent, p) {
                data1.push(parent);
                parent.start = 0;
                parent.end = parent.value;
                parent.class = "positive";
                var cumulative = parent.end;
                if (parent.values != undefined) {
                    parent.values.forEach(function (children) {
                        children.class = "negative";
                        data1.push(children);

                        children.start = cumulative;
                        cumulative -= children.value;
                        children.end = cumulative;
                    });
                }
            });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.