Reputation: 397
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}
Upvotes: 0
Views: 387
Reputation: 12039
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)
Upvotes: 3
Reputation: 386868
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);
Upvotes: 1
Reputation: 1
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.
Upvotes: 0