Reputation: 183
I have array data like this
[{id:1, cost:20, range:15} {id:2, cost:30, range:13}]
I want to make array data using jquery like this
cost : [20, 30]
range : [15, 13]
Please tell me how to do that.
Upvotes: 3
Views: 6585
Reputation: 115282
Use forEach
method to iterate and push values to array
var cost = [],
range = [];
var data = [{
id: 1,
cost: 20,
range: 15
} ,{
id: 2,
cost: 30,
range: 13
}];
data.forEach(function(v) {
cost.push(v.cost);
range.push(v.range);
});
console.log(cost, range);
Or with map()
method and generate array
var data = [{
id: 1,
cost: 20,
range: 15
}, {
id: 2,
cost: 30,
range: 13
}];
var cost = data.map(function(v) {
return v.cost;
});
var range = data.map(function(v) {
return v.range;
});
console.log(cost, range);
Upvotes: 2
Reputation: 386883
You could use Array#forEach()
and an object for the result and an array for the wanted properties to group.
var array = [{ id: 1, cost: 20, range: 15 }, { id: 2, cost: 30, range: 13 }],
result = {};
array.forEach(function (a) {
['cost', 'range'].forEach(function (k) {
result[k] = result[k] || [];
result[k].push(a[k]);
});
});
console.log(result);
Upvotes: 0