1const names = ['Alex', 'Bob', 'Johny', 'Atta'];
2
3// convert array to th object
4const obj = Object.assign({}, names);
5
6// print object
7console.log(obj);
8
9// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}
10
1const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
2
3// Example
4toObject(
5 [
6 { id: '1', name: 'June', gender: 'Female' },
7 { id: '2', name: 'Alex', gender: 'Male' },
8 { id: '3', name: 'Harry', gender: 'Male' },
9 ],
10 'id'
11);
12/*
13{
14 '1': { id: '1', name: 'June', gender: 'Female' },
15 '2': { id: '2', name: 'Alex', gender: 'Male' },
16 '3': { id: '3', name: 'Harry', gender: 'Male' },
17}
18*/
1const array = [ [ 'cardType', 'iDEBIT' ],
2 [ 'txnAmount', '17.64' ],
3 [ 'txnId', '20181' ],
4 [ 'txnType', 'Purchase' ],
5 [ 'txnDate', '2015/08/13 21:50:04' ],
6 [ 'respCode', '0' ],
7 [ 'isoCode', '0' ],
8 [ 'authCode', '' ],
9 [ 'acquirerInvoice', '0' ],
10 [ 'message', '' ],
11 [ 'isComplete', 'true' ],
12 [ 'isTimeout', 'false' ] ];
13
14const obj = Object.fromEntries(array);
15console.log(obj);
1function arrayToObject(arr) {
2 var obj = {};
3 for (var i = 0; i < arr.length; ++i){
4 obj[i] = arr[i];
5 }
6 return obj;
7}
8var colors=["red","blue","green"];
9var colorsObj=arrayToObject(colors);//{0: "red", 1: "blue", 2: "green"}