Search code examples
javascriptarraysjsond3.jssub-array

d3.js: extract array in object within array


I would like to obtain array in object within array.

Original structure:
Array [ object, ..., object ]

var dateC = [ 
      {
      key: "2016-01-01",
      values: **[
        {city:"", country:""...},
        {...}
      ]**},
      {
      key: "2016-01-02",
      values: [
        {...},
        {...}
      ]}
]

var dateC2 = dateC.filter(function(d) { return d.key == selected; }).map(function(d) { return d.values })

I extracted the object from dateC that has key: "2016-01-01" using the above code.

Current structure:
Array [ Array[114] ]

var dateC2 = [ 
  {
  key: "2016-01-01",
  values: **[
    {city:"", country:""...},
    {...}
  ]**}
]

Desired structure:
Array [ Object, ..., Object ]

**[{city:"", country:""...}, {...}]**

Array that I want is contained by **

I am not sure how I should use forEach method to get the array from values because I have already use filter and map on dateC to obtain dateC2. Alternatively, is there a quicker way to obtain the desired structure from original structure?


Solution

  • You could use a single loop for it with Array#reduce.

    var dateC2 = dateC.reduce(function(r, d) {
        return d.key == selected ? 
            r.concat(d.values):
            r;
    }, []);