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

1 Answer 1

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]]]]]]));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.