d3.nest()键/值未定义的值

时间:2019-02-06 14:47:14

标签: javascript d3.js nested key-value

我正在尝试在嵌套数据后从 key / 中获取所有 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);

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您只需要映射到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)