Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing JSON

I'd like to extract all the properties of a homogeneous JSON collection into it's 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'd like to extract an array of all Values from dataPoints that looks something like:

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

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

like image 322
bjaxbjax Avatar asked Aug 12 '26 15:08

bjaxbjax


1 Answers

Ultimately, you're going to need to do some iteration.

A map function is 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 an external library's map function:

  • Prototype - collect
  • jQuery.map
  • Underscore - map
like image 199
namuol Avatar answered Aug 15 '26 05:08

namuol