简体   繁体   中英

get specific data from multidimensional array jquery

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM