Convert Arrays in an Object to an Object in Javascript

I was working with an object in Javascript, and I needed to convert all arrays in the object to an object itself no matter the level the Array was present in the object. Here's what I came up with:

const convertArrayInObject = (obj) => {
  return JSON.parse(JSON.stringify(obj, (key, value) => {
          const convertedTOOBject = value.reduce((obj, cur, index) => ({...obj, [index]: cur}), {});
          return convertedTOOBject;
      return value;

The above code snippet takes advantage of the replace callback parameter in the JSON.stringify function (here's an article that explains it).

It checks for every value in the object, if it's an array, and then converts to an object using the index as the key.

Pretty simple - and with the above, we get:

// input
// {
//   "name": "Edwards",
//   "links": ["", ""],
//   "age": 23
// }

// output 
// {
//     "name": "Edwards",
//     "links": {
//         "0": "",
//         "1": ""
//     },
//     "age": 23
// }


Edwards Moses - Web & Mobile — React & React Native Consultant

Edwards Moses
Web & Mobile — React & React Native Consultant

I'm Edwards, based in Lagos, Nigeria.
Freelancer Software Developer — collaborating with teams to craft extraordinary products.
From conception through to completion, I find immense joy in witnessing the evolution of an idea into a fully realized product in the hands of users.

Ready to bring your ideas to life? Let's connect