0

I need to convert an array into object with key values.For Example

var Array = [17.3850, 78.4867]

I need to convert into Object in this manner

var Object = {"lat":17.3850, "lng":78.4867}
MH2K9
  • 11,951
  • 7
  • 32
  • 49
Pavan Kusunuri
  • 327
  • 5
  • 20

3 Answers3

3

Using Array.prototype.map() make an iteration over the array, create an array of Object and finally convert that to an object using Object.assign().

var key = ['lat', 'lng'];
var array = [17.3850, 78.4867]


var obj = Object.assign({}, ...key.map((e, i) => ({[e]: array[i]})))
console.log(obj)
MH2K9
  • 11,951
  • 7
  • 32
  • 49
1

You could map an array with arrays of key/value pairs and create an object with Object.fromEntries.

var array = [17.3850, 78.4867],
    keys = ['lat', 'lng'],
    object = Object.fromEntries(array.map((v, i) => [keys[i], v]));

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

you can use the constructor in JavaScript.

class Location {
  constructor(lat, lng) {
   this.lat = lat,
   this.lng = lng
  }
}
var myArray = [17.3850, 78.4867];
var myLocation = new Location(myArray[0], myArray[1]);
myLocation.lat;
myLocation.lng;

Instead of myArray[0] & myArray[1] you can use loop to make it dynamic.