映射键并创建一个新对象

时间:2018-06-13 04:56:12

标签: javascript

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

创建一个数组:

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

如何动态映射键,以便我有这样的对象:

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

2 个答案:

答案 0 :(得分:3)

这可以使用数组解构:

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

console.log(output);

答案 1 :(得分:0)

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