简体   繁体   中英

How to convert array of objects to array of arrays in js

var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}]

I want to convert that to

[[1231,121],[131,11],..]

So far I have tried Array.prototype.slice.call but it is not working for me.

Use Array.prototype.map method. It iterates over an array and creates new one with the items returned by each iteration:

 var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}]; var result = ph.map(function(el) { return [el.x, el.y]; }); document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>'

ES6 syntax would also allow more concise notation:

var result = ph.map(el => [el.x, el.y]);

You can use map() to iterate and generate new array based on old array elements.

 var arr = [{ x: 1231, y: 121 }, { x: 131, y: 11 }, { x: 231, y: 21 }, { x: 123, y: 12 }]; var res = arr.map(function(v) { return [v['x'], v['y']]; }); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

You can use Array.prototype.map . In ES6 it can done like

 var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}]; var arr = ph.map(elem => [elem.x, elem.y]); document.write(JSON.stringify(arr));

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