将数组中的数组转换为对象

时间:2017-08-22 01:38:24

标签: javascript arrays javascript-objects

转换的最佳方式

a = [['tokyo', '10', '20'],['newyork', '30', '40'],['singapore', '50', '60']];

a = [{city:'tokyo', lat:'10', lon:'20'},{city:'newyork', lat:'30', lon:'40'},{city:'singapore', lat:'50', lon:'60'}];

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用#map()函数将其转换为对象的数组 - 请参阅下面的演示:

var a = [['tokyo', '10', '20'],['newyork', '30', '40'],['singapore', '50', '60']];

var result = a.map(function(e) {
  return {
    city: e[0],
    lat: e[1],
    lon: e[2]
  }
},[]);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

答案 1 :(得分:1)

不确定最佳方式,但我认为它是可读的。它使用一个名为public Form1() { InitializeComponent(); pictureBox1.Hide(); pictureBox2.Hide(); Positions(); this.StartPosition = FormStartPosition.Manual; this.FormBorderStyle = FormBorderStyle.None; SetScreen.setFormLocation(this, Screen.PrimaryScreen); Form2 f = new Form2(); f.StartPosition = FormStartPosition.Manual; f.FormBorderStyle = FormBorderStyle.None; SetScreen.setFormLocation(f, Screen.AllScreens[1]); f.Show(); } 的方法,该方法遍历数组中的每个元素,并且通常根据您的喜好对其进行修改。有关示例,请参阅以下代码。

.map()

此处的MDN参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

相关问题