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:

Copy
const convertArrayInObject = (obj) => {
  return JSON.parse(JSON.stringify(obj, (key, value) => {
      if(Array.isArray(value)){
          const convertedTOOBject = value.reduce((obj, cur, index) => ({...obj, [index]: cur}), {});
          console.log(convertedTOOBject);
          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:

Copy
// input
// {
//   "name": "Edwards",
//   "links": ["https://edwardsmoses.com", "https://google.com"],
//   "age": 23
// }

// output 
// {
//     "name": "Edwards",
//     "links": {
//         "0": "https://edwardsmoses.com",
//         "1": "https://google.com"
//     },
//     "age": 23
// }

Comments

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. Check out my projects and articles to see what I've been up to lately.

Ready to bring your ideas to life?