Max Do
Max Do

Reputation: 21

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!

Upvotes: 0

Views: 41

Answers (2)

Christopher Messer
Christopher Messer

Reputation: 2090

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. 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

Upvotes: 1

kukkuz
kukkuz

Reputation: 42352

You can use #map() function to convert it into the array of objects - see demo below:

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

Upvotes: 2

Related Questions