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

3 Answers 3

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)

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

Comments

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

Comments

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.

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.