最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using dictionary as D3 data source - Stack Overflow

programmeradmin2浏览0评论

I want to use this data (below) as a data source for a d3.js program:

{
  "ponent": {
    "name1": {
      "graphname": {
        "title": "foo",
        "data": [
          {"data": "DATE IN ISOFORMAT", "value": 5},
          {"data": "DATE IN ISOFORMAT", "value": 10}
          ]
      }
    },
    "name2": {
      "graphname": {
        "title": "foo",
        "data": [
          {"data": "DATE IN ISOFORMAT", "value": 5},
          {"data": "DATE IN ISOFORMAT", "value": 10}
          ]
      }
    }
  }
  "ponent2": {...
}

D3 accepts only array data? How i can manipulate it to work?

I want to graph for all ponent any "graphname" aggregated by "name"

Any tips?

I want to use this data (below) as a data source for a d3.js program:

{
  "ponent": {
    "name1": {
      "graphname": {
        "title": "foo",
        "data": [
          {"data": "DATE IN ISOFORMAT", "value": 5},
          {"data": "DATE IN ISOFORMAT", "value": 10}
          ]
      }
    },
    "name2": {
      "graphname": {
        "title": "foo",
        "data": [
          {"data": "DATE IN ISOFORMAT", "value": 5},
          {"data": "DATE IN ISOFORMAT", "value": 10}
          ]
      }
    }
  }
  "ponent2": {...
}

D3 accepts only array data? How i can manipulate it to work?

I want to graph for all ponent any "graphname" aggregated by "name"

Any tips?

Share Improve this question edited Mar 10, 2017 at 11:48 Jonathan Eunice 22.5k8 gold badges79 silver badges78 bronze badges asked Mar 10, 2017 at 11:16 KaylasKaylas 1121 gold badge2 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

D3 does not just accept arrays as data sources, but for looping purposes, arrays are much more convenient than JavaScript objects ("dicts"). There is a very easy way to convert objects to arrays, though. If your object above were called d, then its corresponding array can be created with:

var dlist = d3.entries(d);

Now dlist will be something like:

[ { key: 'ponent',
    value: { name1: ..., name2: ... } },
  { key: 'ponent2',
    value: { name1: ..., name2: ... } } ]

The original dict has been remapped into an array of "records," each with key and value pairs. This "array of records" pattern is very mon in D3 work, and JavaScript in general. If you need to loop over the sub-structures (e.g. the name1, name2, ... values, d3.entries can be applied at multiple levels of the original structure, as those dict-to-list transforms are required.

Since this answer is called out in the ments as wrong, here's a working example of using an object ("dict") as a data source for a D3 program: first in a simple loop, then secondarily using the idiomatic d3 .data(...).enter() pipeline.

发布评论

评论列表(0)

  1. 暂无评论