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.
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!
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With