简体   繁体   中英

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:

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

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