简体   繁体   English

映射键并创建一个新对象

[英]Map keys and create a new object

var str = "145.10880940000004,-37.9333893,10"
var view = str.split(",");
console.log(view);

Creates an array: 创建一个数组:

[
  "145.10880940000004",
  "-37.9333893",
  "10"
]

How do I dynamically map the keys so I have an object like this: 我如何动态映射键,以便有一个像这样的对象:

{
  Lng: "145.10880940000004",
  Lat: "-37.9333893",
  Zoom: "10"
}

This would work, using array destructuring: 使用数组解构,这将起作用:

 const input = "145.10880940000004,-37.9333893,10"; const [Lng, Lat, Zoom] = input.split(','); const output = {Lng, Lat, Zoom}; console.log(output); 

Similar to @Robby Cornelissen's answer, if you have multiple of these values, you can do this neatly with .map and parameter destructuring: 与@Robby Cornelissen的答案类似,如果您拥有多个这些值,则可以使用.map和参数解构来巧妙地做到这一点:

 const values = [ "145.10880940000004,-37.9333893,10", "145.10880940000004,-37.9333893,10", ]; console.log( values .map(str => str.split(',')) .map(([Lng, Lat, Zoom]) => ({Lng, Lat, Zoom})) ); 

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

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