Javascript Object to Array and visa versa

const obj = {"1":"5","2":7,"3":9,"4":155,"6":"189","7":587,"8":"455","9":"89","10":"80","12":"887.6","13":89,"14":9}
const objToArr = Object.keys(obj).map(function(key) {
  return [key, Number(obj[key]) ];
});
console.log(objToArr)
/*
[ [ '1', 5 ],
  [ '2', 7 ],
  [ '3', 9 ],
  [ '4', 155 ],
  [ '6', 189 ],
  [ '7', 587 ],
  [ '8', 455 ],
  [ '9', 89 ],
  [ '10', 80 ],
  [ '12', 887.6 ],
  [ '13', 89 ],
  [ '14', 9 ] ]
*/


let resultObj = objToArr.reduce(function(result, item, index, array) {
   Object.assign(result, { [ item [ 0 ] ]:item[1]} )
  return result;
}, {}) //watch out the empty {}, which is passed as "result"
console.log(resultObj)
/*
{ '1': 5,
  '2': 7,
  '3': 9,
  '4': 155,
  '6': 189,
  '7': 587,
  '8': 455,
  '9': 89,
  '10': 80,
  '12': 887.6,
  '13': 89,
  '14': 9 }
*/

resultObj2 = {...objToArr};
console.log(resultObj2)
/*
{ '0': [ '1', 5 ],
  '1': [ '2', 7 ],
  '2': [ '3', 9 ],
  '3': [ '4', 155 ],
  '4': [ '6', 189 ],
  '5': [ '7', 587 ],
  '6': [ '8', 455 ],
  '7': [ '9', 89 ],
  '8': [ '10', 80 ],
  '9': [ '12', 887.6 ],
  '10': [ '13', 89 ],
  '11': [ '14', 9 ] }
*/





Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image