D3js получает массив ключей для рисования диаграммы из json - PullRequest
0 голосов
/ 19 января 2019

У меня есть объект json с несколькими ключами и данными внутри, текущий код берет только первый ключевой объект и рисует его. Я хочу, чтобы каждый ключ создавал элемент, в настоящее время только берет первый ключ и рисует его.

Каждый элемент ключевого объекта будет создаваться динамически. Пожалуйста, помогите с этим

Данные Json, которые содержат два объекта и будут увеличиваться по мере того, как я продолжаю динамически добавлять:

    var processMain = {
            "process": [{
                "ProcessName" : "Record One", 
                "Username" : "Joh Doe", 
                "Created" : "10:00:00",
                'records': [
                  "Titles goes here",
                  "This is another title"
                ],
                'display': [
                  {
                    'question': "Question one",
                    'answer': "answer goes here"
                  },
                  {
                    'question': "Question Two",
                    'answer': "answer goes here"
                  }
                ]
            }],
            "chapterOne": [{
                "ProcessName" : "Second Record", 
                "Username" : "Joh Hoe", 
                "Created" : "10:00:00",
                'records': [
                  "Titles goes here",
                  "This is another title"
                ],
                'display': [
                  {
                    'question': "Question one",
                    'answer': "answer goes here"
                  },
                  {
                    'question': "Question Two",
                    'answer': "answer goes here"
                  }
                ]
            }]
        }; 

Рабочий Fiddle, который я пытался получить, поскольку цикл не помог мне создать ожидаемые элементы: https://jsfiddle.net/vickyparab76/y0duk4je/3/

Что я пробовал? Циклический просмотр ключей, но выводит больше ожидаемых элементов

    for (var propName in processMain) {
        if (processMain.hasOwnProperty(propName)) {
          // console.log(propName);
        }
    }

HTML:

    <svg style="padding-top: 100px" class="chart">
      <marker id="arrow" markerWidth="10" markerHeight="10" refx="0" refy="3" orient="auto" markerUnits="strokeWidth" viewBox="0 0 10 10">
        <path d="M0,0 L0,6 L9,3 z" fill="#5091CF" />
      </marker>
    </svg>

JS:

var processMain = {
    "process": [{
        "ProcessName" : "Record One", 
        "Username" : "Joh Doe", 
        "Created" : "10:00:00",
        'records': [
          "Titles goes here",
          "This is another title"
        ],
        'display': [
          {
            'question': "Question one",
            'answer': "answer goes here"
          },
          {
            'question': "Question Two",
            'answer': "answer goes here"
          }
        ]
    }],
    "chapter-one": [{
        "ProcessName" : "Second Record", 
        "Username" : "Joh Hoe", 
        "Created" : "10:00:00",
        'records': [
          "Titles goes here",
          "This is another title"
        ],
        'display': [
          {
            'question': "Question one",
            'answer': "answer goes here"
          },
          {
            'question': "Question Two",
            'answer': "answer goes here"
          }
        ]
    }]
};

var data = processMain.process
// console.log(processMain[Object.keys(processMain)[0]]);

for (var propName in processMain) {
    if (processMain.hasOwnProperty(propName)) {
        // console.log(propName);
    }
}
d3.values(processMain).map(function(d) { 
    console.log(d.category); 
})

//initialize width and height
var width = 180,
    barHeight = 100;
    lineHeight = 100;

// selecting svg and setting the height of main element
var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", ((barHeight+lineHeight) * data.length));

//adding gropu for each process
var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * (barHeight+lineHeight+10) + ")"; });


//creating vertical line with arrow marker
bar.append('line')
    .attr("x1",width/2) 
    .attr("y1","0") 
    .attr("x2",width/2) 
    .attr("y2",lineHeight-15)
    .attr("transform","translate(0,-"+(lineHeight+5)+")")
    .attr("stroke","#5091CF") 
    .attr("stroke-width","2")
    .attr("marker-end","url(#arrow)")

//spawned process background
bar.append("rect")
    .attr("width", width)
    .attr("height", 15)
    .attr("x", 0)
    .attr("transform","translate(0,-"+(lineHeight*.85)+")")
    .attr("y", barHeight / 6 )

    .attr("fill", "#fff")
    .text(function(d) { return ''});

//spawned process text
var ltext = bar.append("text")
    .attr("text-anchor","middle")
    .attr("x", 0)
    .attr("class","spawned")
    .attr("transform","translate("+width/2+",-"+(lineHeight*.85)+")")
    .attr("y", barHeight / 4)
    .attr("dy", ".35em")
    .attr("fill", "#5091CF")
    .text(function(d) { return ''});
ltext.append("tspan")
    .attr("x",0)
    .attr("y", (barHeight / 4))
    .attr("dy", ".35em")
    .attr("text-anchor","middle")
    .text(function(d) { return "spawned process"; });

//process rectangle  
bar.append("rect")
    .attr("width", width)
    .attr("class","prect")
    .attr("height", barHeight - 1);

//process text
var text = bar.append("text")
    .attr("text-anchor","middle")
    .attr("x", 0)
    .attr("transform","translate("+width/2+")")
    .attr("y", barHeight / 4)
    .attr("dy", ".35em")
    .text(function(d) { return ''});

//process name
text.append("tspan")
    .attr("x",0)
    .attr("y", (barHeight / 4))
    .attr("dy", ".35em")
    .attr("class",'pname')
    .attr("text-anchor","middle")
    .text(function(d) { return d.ProcessName; });

//process user name
text.append("tspan")
    .attr("x",0)
    .attr("y", (barHeight / 3)*1.8)
    .attr("dy", ".35em")
    .attr("text-anchor","middle")
    .text(function(d) { return 'User : '+d.Username; });

//process created date
text.append("tspan")
    .attr("text-anchor","middle")
    .attr("x", 0  )
    .attr("y", (barHeight /3)*2.3)
    .attr("dy", ".35em")
    .text(function(d) { return 'Created : '+d.Created; });

//appending test
bar.append("g")
.attr("transform", function(d, i) { return "translate("+width+",0)"; })

.selectAll("li")
  .data(function(d) { return d.operation; })

.enter().append("circle")
  .text(function(d) { return d.hour + ": " + d.hits; });

ожидаемый результат: enter image description here

...