0

I want to write a code in javascript to convert a nested array in to a nested object. The point is every single elements in the nested array would be an array itself, so should convert to a nested object:

Examples:

  • [['a', 1], ['b', 2], ['c', [['d', 4]]]] => { a: 1, b: 2, c: { d: 4 } }
  • [['a', 1], ['b', 2], ['c', [['d', [['e', 5], ['f', 6]]]]]] => { a: 1, b: 2, c: { d: { e: 5, f: 6 } } }

I tried to go with this concept: define a function to iterate over the base array. for every single element, it will make a key:value for the object. if the value is an array, the function will call itself. but Actually I dont know how to write it.

const nestedArrayToObject = function (arr) {
  let obj = {};
  for (let i = 0; i < arr.length; i++) {
      let key = arr[i][0];
      let val = arr[i][1];
      if (!Array.isArray(val)) {
        obj[key] = val;
      } else {
        nestedArrayToObject(val); ???
      }
  }
  return obj;
 };
  • 1
    Does this answer your question? [Converting nested arrays to objects](https://stackoverflow.com/questions/63810162/converting-nested-arrays-to-objects) – Toribio Jan 27 '23 at 20:47

1 Answers1

1

You can use Object.fromEntries to convert an array of key-value pairs to an object. For each value that is also an array, recursively call the conversion function.

function convert(arr) {
  return Object.fromEntries(arr.map(([k, v]) => 
            [k, Array.isArray(v) ? convert(v) : v]));
}
console.log(convert([['a', 1], ['b', 2], ['c', [['d', 4]]]]));
console.log(convert([['a', 1], ['b', 2], ['c', [['d', [['e', 5], ['f', 6]]]]]]));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80