简体   繁体   中英

Converting an array to object in JavaScript

I have a dynamically created array like this on the client side.

value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

and I need to store it in an object format in this order with adding new "spatialReference": {"wkid": 4326 }

   var params = [
     {
       "x": -88.17179185999998,
       "y": 41.78264698400005,
       "spatialReference": {"wkid": 4326 }
     }, 
     {
       "x": -88.17193080699997,
       "y": 41.782605419000056,
       "spatialReference": {"wkid": 4326 }
     }
   ];

How can I do this?

You can simply use .map() :

 const value = [ [-88.17179185999998, 41.78264698400005], [-88.17193080699997, 41.782605419000056] ]; const objs = value.map(([x, y]) => ({ x, y, spatialReference: {wkid: 4326 } })); console.log(objs); 

.map() just goes through each element, and runs some function against it, and uses the results of that to make a new array. Very easy for converting elements in an array from a to b.

Use map to create array of objects:

 var value = [ [-88.17179185999998, 41.78264698400005], [-88.17193080699997, 41.782605419000056] ] var data = value.map(function(elem) { return { x: elem[0], y: elem[1], spatialReference: { wkid: 4326 } } }) console.log(data) 

Or using es6:

 const value = [ [-88.17179185999998, 41.78264698400005], [-88.17193080699997, 41.782605419000056] ] let data = value.map(elem => ({ x: elem[0], y: elem[1], spatialReference: { wkid: 4326 } })) console.log(data) 

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