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
},
{
开发者_如何学Python "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?
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
you can probably do some interesting things by creating your own map function depending on what you need to do with it ... but at the end of the day, you will end up iterating the original array and pulling out the value you are interested in
Just for fun, given this method:
function project(a, fn)
{
var list = new Array();
for (i = 0; i < a.length; i++)
{
list.push(fn(a[i]));
}
return list;
}
You can easily get an array that looks like what you're describing:
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'
I agree with Joel that there's no magic here - you will need to iterate over the array in order to extract the values. The fastest way to iterate over an array is a simple for loop. See here for a good post about array iteration performance. End of the day, even for a very large array, this should not be a very expensive operation if you code it correctly.
One thing I would add for you think about is whether you have the opportunity to change the structure of the data as it's being created. eg: if you have a loop that creates this data, could you also create an array of 'values' at the same time as you create an array of year 'objects'?
精彩评论