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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With