D3.js roll up nested data

178 Views Asked by At

please help me

I've got a json file like this.

 [
{
    "Paket": [
        {
            "farbe": "#ff0000",
            "Koordinaten": [
                {
                    "paketaufenthaltsort": "469\/31 A 1; A 3; A 4",
                    "y": "5",
                    "x": "0"
                },
                {
                    "paketaufenthaltsort": "469\/31 A 1; A 3; A 4",
                    "y": "5",
                    "x": "150"
                },
                {
                    "paketaufenthaltsort": "469\/31 A 1; A 3; A 4",
                    "y": "0",
                    "x": "150"
                }
            ],
            "Paketnummer": "11000005"
        }
    ],
    "offset": "5",
    "referenzzeitraum": "1440"
}
 ]

and now I want to have an array containing all values of "paketaufenthaltsort".

So I've tried the following:

console.log(data.map(function(d)
{return d.Paket.map(function(e) 
{return e.Koordinaten.map(function(f) {return
f.paketaufenthaltsort;})})}));

But it produces an array of level 3. The outcome is:

   [[["469/31 A 1; A 3; A 4", "469/31 A 1; A 3; A 4", "469/31 A 1; A 3; A 4"]]]

But what i want is:

["469/31 A 1; A 3; A 4"]

Please help me

2

There are 2 best solutions below

0
On

You can use:

console.log(data.map(function(d){
return d.Paket.map(function(e) 
{return e.Koordinaten.map(function(f) {return
f.paketaufenthaltsort;})})[0][0][0]}));

which will access the first element of the nested array.

0
On

There is no need to call map() on the outer arrays, because you are only interested in the array Koordinaten. Only this array needs to get mapped to the desired output by replacing the contained objects with the value of the property paketaufenthaltsort of each individual object. You will just need to iterate over the outer arrays by invoking Array.prototype.forEach() on each of these arrays:

data.forEach(function(d) {
    d.Paket.forEach(function(p) {
        var orte = p.Koordinaten.map(function(k) {
            return k.paketaufenthaltsort;
        });
        console.log(orte);
    });
});

Check this JSFiddle for a working example.