Edgar Kiljak
Edgar Kiljak

Reputation: 1190

d3.nest() key/value undefined values

I'm trying to get an array of all n values from key/values after nesting data. I've managed to console.log all n values but the end result I'm having is an array of undefined [undefined, ... , undefined].

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

Data after nesting:

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}

Now get all n values:

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

What am I doing wrong?

Upvotes: 2

Views: 467

Answers (1)

calmar
calmar

Reputation: 1959

You just need to map into the values key and return n for each grouped data

 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)

Upvotes: 2

Related Questions