There are couple of ways to achieve this.
Method one is to use Object.Assign().
More information can be found here
Eg:
let arr = ["apple", "strawberry", "banana", "cherry", "tomato", "carrot", "plum"];
let x = Object.assign({}, arr);
//{
// '0': 'apple',
// '1': 'strawberry',
// '2': 'banana',
// '3': 'cherry',
// '4': 'tomato',
// '5': 'carrot',
// '6': 'plum'
// }
Method two is to use Object.fromEntries().
What it does is it transforms a list of key/value pairs in to an object. More information can be found here.
Eg:
let keyValueList = [
["1x", "apple"],
["2x", "strawberry"],
["3x", "banana"],
["4x", "cherry"],
[5, "tomato"],
];
let x = Object.fromEntries(keyValueList);
console.log(x);
// {
// '5': 'tomato',
// '1x': 'apple',
// '2x': 'strawberry',
// '3x': 'banana',
// '4x': 'cherry'
// }
Method two is to use Array.map().
This method creates a new array populated with the results of calling a provided function on every element in the calling array. more information can be found here.
let arr = ["apple", "strawberry", "banana", "cherry", "tomato", "carrot", "plum"];
let y = {};
let x = arr.map((item, index) => { // arr.forEach can also be used here
return (y[index] = item);
});
console.log(y);
// {
// '0': 'apple',
// '1': 'strawberry',
// '2': 'banana',
// '3': 'cherry',
// '4': 'tomato',
// '5': 'carrot',
// '6': 'plum'
// }
There could be more ways to do this as well such a using a for loop and so on.
Comments
Post a Comment