Martin Burch
Martin Burch

Reputation: 2911

d3 data reshape: properties to array

I have some data in this format:

{
    seriesOne: [
        [1, 42.3],
        [2, 12.9]
    ],
    seriesTwo: [
        [1, 23.1],
        [2, 10.6]
    ]
}

But I'm looking at a D3 example where the data is eventually in this format:

[{
        id: "seriesOne",
        values: [{
                x: 1,
                y: 42.3
            },
            {
                x: 2,
                y: 12.9
            }
        ]
    },
    {
        id: "seriesTwo",
        values: [{
                x: 1,
                y: 23.1
            },
            {
                x: 2,
                y: 10.6
            }
        ]
    }
]

Can I draw a chart with this as is? Alternatively, is there a D3 way to reshape my data?

I can reshape this with plain old JS, but this seems inefficient.

var reshapedData = [];
Object.keys(originalData).forEach(function (key) {
   currentSeries = {id: key, values: []};
   originalData[key].forEach(function (value) {
      currentSeries['values'].push({x: value[0], y: value[1]});
   });
   reshapedData.push(currentSeries);
});

Upvotes: 1

Views: 345

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can use reduce() method and inside map() method to create values array of objects.

const data = {"seriesOne":[[1,42.3],[2,12.9]],"seriesTwo":[[1,23.1],[2,10.6]]}
const result = Object.keys(data).reduce((r, id) => {
  r.push({id, values: data[id].map(([x, y]) => ({x, y}))})
  return r;
}, [])

console.log(result)

Upvotes: 1

Related Questions