3

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.

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

@ArieSastra : glad to help you :)
0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.