简体   繁体   English

在JavaScript中将数组转换为对象

[英]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 } 并且我需要以添加新"spatialReference": {"wkid": 4326 }顺序将其以对象格式存储"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() : 您可以简单地使用.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. .map()仅遍历每个元素,并对它运行一些功能,然后使用该结果生成一个新数组。 Very easy for converting elements in an array from a to b. 从a到b转换数组中的元素非常容易。

Use map to create array of objects: 使用map创建对象数组:

 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: 或使用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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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