[英]Making an Array in an Array into Objects
Best way to convert 转换的最佳方法
a = [['tokyo', '10', '20'],['newyork', '30', '40'],['singapore', '50', '60']];
to 至
a = [{city:'tokyo', lat:'10', lon:'20'},{city:'newyork', lat:'30', lon:'40'},{city:'singapore', lat:'50', lon:'60'}];
Thanks! 谢谢!
You can use #map()
function to convert it into the array of objects - see demo below: 您可以使用
#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;}
Not sure about best way, but I think it's readable. 不确定最好的方法,但我认为它是可读的。 It uses a method called
.map()
that goes through each element in an array, and typically modifies it to your liking. 它使用称为
.map()
的方法遍历数组中的每个元素,并通常根据您的喜好对其进行修改。 See the below code for an example. 有关示例,请参见下面的代码。
a = [['tokyo', '10', '20'],['newyork', '30', '40'],['singapore', '50',
'60']];
const newArrayOfObjects = a.map(val => {
return { city: val[0], lat: val[1], lon: val[2] }
})
newArrayOfObjects
MDN reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 此处的MDN参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.