Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Whats the best way Convert Array into Object? [duplicate]

what is the best way to convert:

a = ['USD', 'EUR', 'INR']

to

a = {'USD': 0, 'EUR': 0, 'INR': 0};

*manipulating array element as key of objects with value as initially 0.

like image 655
Shishir Sonekar Avatar asked Jan 24 '17 11:01

Shishir Sonekar


People also ask

What is the best way to turn an array into an object using JavaScript?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied!

How do you transform an array into an object?

To convert an array into an object we will create a function and give it 2 properties, an array and a key. const convertArrayToObject = (array, key) => {}; We will then reduce the array, and create a unique property for each item based on the key we have passed in.

How do you convert two arrays into objects?

To convert two arrays into a JSON object, we have used the forEach() method to iterate over the first array. we have used the index to get the element from the second array. On every iteration forEach() method will assign the key-value pair to a JSON object.

How do you duplicate an array?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


1 Answers

Use Array#reduce method to reduce into a single object.

a = ['USD', 'EUR', 'INR'];

console.log(
  a.reduce(function(obj, v) {
    obj[v] = 0;
    return obj;
  }, {})
)

Or even simple for loop is fine.

var a = ['USD', 'EUR', 'INR'];
var res = {};

for (var i = 0; i < a.length; i++)
  res[a[i]] = 0;

console.log(res);
like image 117
Pranav C Balan Avatar answered Oct 07 '22 03:10

Pranav C Balan