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 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"}
1// This function counts instances of elements in an array
2// the return object has the array elements as keys
3// and number of occurrences as it's value
4const arrToInstanceCountObj = arr => arr.reduce((obj, e) => {
5 obj[e] = (obj[e] || 0) + 1;
6 return obj;
7}, {});
8
9arrToInstanceCountObj(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'])
10/*
11 {
12 h: 1,
13 e: 1,
14 l: 3,
15 o: 2,
16 w: 1,
17 r: 1,
18 d: 1,
19 }
20*/