【问题标题】:d3.nest() key/value undefined valuesd3.nest() 键/值未定义值
【发布时间】:2019-02-06 23:43:12
【问题描述】:

我试图在嵌套数据后从 key/values 中获取所有 n 个值 的数组。我已经设法 console.log 所有 n 个值,但我得到的最终结果是一个未定义的 [undefined, ... , undefined] 数组。

//Nesting data by category
let updatedData = d3.nest()
            .key(d => d.category)
            .sortValues((a, b) =>  a.year - b.year)
            .entries(data);

嵌套后的数据:

key: "clothing, beauty, & fashion"
values: Array(11)
0: {year: 2004, category: "clothing, beauty, & fashion", n: 141}
1: {year: 2005, category: "clothing, beauty, & fashion", n: 203}
2: {year: 2006, category: "clothing, beauty, & fashion", n: 195}
3: {year: 2007, category: "clothing, beauty, & fashion", n: 296}


key: "computers & internet"
values: Array(11)
0: {year: 2004, category: "computers & internet", n: 2489}
1: {year: 2005, category: "computers & internet", n: 2200}
2: {year: 2006, category: "computers & internet", n: 2114}
3: {year: 2007, category: "computers & internet", n: 2402}

现在获取所有 n 个值:

const nValues = [].concat.apply([], updatedData.map(d => d.values[d.values.forEach(d => console.log(d.n))]));
console.log(nValues);

我做错了什么?

【问题讨论】:

    标签: javascript d3.js nested key-value


    【解决方案1】:

    您只需映射到values 键并为每个分组数据返回n

     const nValues = data.map(group => group.values.map(e=> e.n))
    

    const data = [
      {
        "key": "clothing, beauty, & fashion",
        "values": [
          {
            "year": 2004,
            "category": "clothing, beauty, & fashion",
            "n": 141
          },
          {
            "year": 2005,
            "category": "clothing, beauty, & fashion",
            "n": 203
          },
          {
            "year": 2006,
            "category": "clothing, beauty, & fashion",
            "n": 195
          },
          {
            "year": 2007,
            "category": "clothing, beauty, & fashion",
            "n": 296
          }
        ]
      },
      {
        "key": "computers & internet",
        "values": [
          {
            "year": 2004,
            "category": "computers & internet",
            "n": 2489
          },
          {
            "year": 2005,
            "category": "computers & internet",
            "n": 2200
          },
          {
            "year": 2006,
            "category": "computers & internet",
            "n": 2114
          },
          {
            "year": 2007,
            "category": "computers & internet",
            "n": 2402
          }
        ]
      }
    ]
     
     const nValues = data.map(group => group.values.map(e=> e.n))
     console.log(nValues)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2019-04-05
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多