Go through JSON to construct waterfall graph D3

0

I need to construct a graph in waterfall and I'm having trouble scrolling through the JSON to construct this graph.

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 required to create a parent column and each value has its expense " name " and the amount of that expense " value ". I'm having trouble creating a for that runs through this data structure. using for , it takes only the first value; and using the

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 undefined would be the properties ' value ' of primary key and the rest is coming correctly. Thank you in advance.

    
asked by anonymous 21.08.2018 / 13:17

1 answer

0

I was able to solve the problem by going through the JSON I used two foreach: one to go through the first level and another to go through the second level, if there are any objects.

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;
                    });
                }
            });
    
28.08.2018 / 15:29