0

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!

3
  • 3
    What have you tried yourself? I'd use Array.prototype.map. Commented Aug 22, 2017 at 1:40
  • Sorry but the example you have given is not correctly formatted so it's confusing what you really want to get. there's a "{" that is not closed anywhere. Not clear, do you want all those items to be in one object or an array of objects ? Either way you can use reduce on arrays to do quite a lot' Commented Aug 22, 2017 at 1:53
  • Edited it should be clearer now. I meant to have multiple objects in a single array. Commented Aug 22, 2017 at 1:59

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this worked! Taking a javascript class been stuck on this for a while. Thank you again!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.