xxxxxxxxxx
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
obj[i] = arr[i];
}
return obj;
}
var colors=["red","blue","green"];
var colorsObj=arrayToObject(colors);//{0: "red", 1: "blue", 2: "green"}
xxxxxxxxxx
const names = ['Alex', 'Bob', 'Johny', 'Atta'];
// convert array to th object
const obj = Object.assign({}, names);
// print object
console.log(obj);
// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}
xxxxxxxxxx
// array to object
let data = [
{id: 1, country: 'Germany', population: 83623528},
{id: 2, country: 'Austria', population: 8975552},
{id: 3, country: 'Switzerland', population: 8616571}
];
let dictionary = Object.assign({}, data.map((x) => ({[x.id]: x.country})));
// {1: "Germany", 2: "Austria", 3: "Switzerland"}
xxxxxxxxxx
const array = [ [ 'cardType', 'iDEBIT' ],
[ 'txnAmount', '17.64' ],
[ 'txnId', '20181' ],
[ 'txnType', 'Purchase' ],
[ 'txnDate', '2015/08/13 21:50:04' ],
[ 'respCode', '0' ],
[ 'isoCode', '0' ],
[ 'authCode', '' ],
[ 'acquirerInvoice', '0' ],
[ 'message', '' ],
[ 'isComplete', 'true' ],
[ 'isTimeout', 'false' ] ];
const obj = Object.fromEntries(array);
console.log(obj);
xxxxxxxxxx
// Convert an Array to an Object in JavaScript
// Method 1: Using the Spread Operator
// Input array
let arr = ["chetan", "ujesh", "vishal", "akshay"];
const obj1 = {arr};
console.log(obj1); // { '0': 'chetan', '1': 'ujesh', '2': 'vishal', '3': 'akshay' }
// Method 2: using Object.assign()
let obj2 = Object.assign({}, arr);
console.log(obj2); // { '0': 'chetan', '1': 'ujesh', '2': 'vishal', '3': 'akshay' }
// Method 3: Using JavaScript for loop
function arrayToObj(arr) {
let obj3 = {};
// Traverse array using loop
for (let i = 0; i < arr.length; ++i){
// Assign each element to object
obj3[i] = arr[i];
}
return obj3;
}
console.log(arrayToObj(arr)); // { '0': 'chetan', '1': 'ujesh', '2': 'vishal', '3': 'akshay' }
// Method 4: Using JavaScript Object.fromEntries()
// Input array
let arr4 = [['JS', 'JavaScript'], ['GFG', 'GeeksforGeeks']];
// Create object
let obj4 = Object.fromEntries(arr4);
// Display output
console.log(obj4); // { JS: 'JavaScript', GFG: 'GeeksforGeeks' }
xxxxxxxxxx
const result = arr.reduce((obj, cur) => ({obj, [cur.sid]: cur}), {})
xxxxxxxxxx
const names = ['Alex', 'Bob', 'Johny', 'Atta'];
const obj = Object.assign({}, names);
console.log(obj);
xxxxxxxxxx
// Also, the following works well:
// IF the array came as follows (you cannot declare an array like that)
const obj = Object.assign({}, ['name': 'Alex', 'age': 43, 'gender': 'male']);
console.log(obj);
xxxxxxxxxx
const result = arr.reduce((obj, cur) => ({obj, [cur.sid]: cur}), {})
xxxxxxxxxx
const names = ['Alex', 'Bob', 'Johny', 'Atta'];
const obj = Object.assign({}, names);