Transpose JSON

I would like to extract all the properties of a homogeneous JSON collection into my own array.

For example, given:

var dataPoints = [
    {
        "Year": 2005,
        "Value": 100 
    },
    {
        "Year": 2006,
        "Value": 97 
    },
    {
        "Year": 2007,
        "Value": 84 
    },
    {
        "Year": 2008,
        "Value": 102 
    },
    {
        "Year": 2009,
        "Value": 88 
    },
    {
        "Year": 2010,
        "Value": 117 
    },
    {
        "Year": 2011,
        "Value": 104 
    }
];

I would like to extract an array of all values ​​from dataPoints, which looks something like this:

var values = [100, 97, 84, 102, 88, 117, 104];

Instead of iterating and constructing manually, is there a clean / efficient way to do this transposition?

+3
source share
3 answers

Ultimately, you will need to do some iteration.

Function

A mapis what you want here:

function map(array, callback) {
    var result = [],
        i;

    for (i = 0; i < array.length; ++i) {
        result.push(callback(array[i]));
    }

    return result;
}

// ...

var values = map(dataPoints, function(item) { return item.Value; });

... or just use the map function of the external library:

+5
source

, , , , ... , .

, :

function project(a, fn)
{
var list = new Array();
    for (i = 0; i < a.length; i++)
    {
        list.push(fn(a[i]));
    }
return list;
}

, , :

var dataPoints = [
    { Year: 2005,
      Value: 100
    },
    { Year: 2006,
      Value: 97
    },
    { Year: 2007,
      Value: 84
    },
    { Year: 2008,
      Value: 102
    },
    { Year: 2009,
      Value: 88
    },
    { Year: 2010,
      Value: 117
    },
    { Year: 2011,
      Value: 104
    }
];

var list = project(dataPoints, function(p) { return p.Value; });

alert(list[0]);  // alerts '100'
+5

, - , . - . . . , , , .

One thing that I would add for you is whether you have the opportunity to change the data structure as it is created. for example: if you have a loop that creates this data, can you also create an array of "values" at the same time as creating an array of "objects of the year"?

0
source

All Articles