DevAchievem
DevAchievem

Reputation: 59

How can I convert a deep nested array into a deep nested object, using recursion?

I'm trying to create a function that will convert an array like this:

[['a', 1], ['b', 2], ['c', [['d', 4]]]]

Into an object like this:

{ a: 1, b: 2, c: { d: 4 } }

So far I just have a function that converts a regular array to regular object, and I'm getting the hang of recursion I'm just not sure how to implement it in such a case. Here is the function that I am working with:

const deepArrayToObject = function(arr) {
  let obj = {};
  if (arr !== []) {
    return obj;
  }
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      let key = arr[i][0];
      let value = arr[i][1];
      obj[key] = value;
    }
  }
  return obj;
};

I appreciate the feedback.

Upvotes: 1

Views: 1098

Answers (2)

fubar
fubar

Reputation: 17388

The trick would be to check whether the value of a given property is an array. If it is, call the function again on the value, otherwise use the value as is.

Here's a version using Array.prototype.reduce.

const a = [['a', 1], ['b', 2], ['c', [['d', 4]]]];

const o = arrayToObject(a);
console.log(o);

function arrayToObject(a) {
  return a.reduce((o, [k, v]) => Object.assign(o, {
   [k]: Array.isArray(v) ? arrayToObject(v) : v,
  }), {});
}

The Object.assign function allows you to append the properties of one or more objects onto a target object.

In the example below, the properties of object b will be appended to object a and a returned. Therefore a and c are the same object.

const a = { a: 'A' };
const b = { b: 'B' };
const c = Object.assign(a, b);

console.log(a, c, a === c);

The ternary operator is a short-hand if statement. In the function it is checking if v is an array. If it is, the array value is passed to the function again initiating the recursive call.

It could be rewritten:

if (Array.isArray(v)) {
    return arrayToObject(v);
} else {
    return v;
}

Upvotes: 2

user12407908
user12407908

Reputation:

You need only one loop, and for the value, check to see which you have, and if it's an array, do the recursion.

const deepArrayToObject = function(arr) {
  let obj = {};

  // This does nothing useful
  //  if (arr !== []) {
  //    return obj;
  //  }

  for (let i = 0; i < arr.length; i++) {
    let key = arr[i][0];
    let value = arr[i][1];
    
    if (Array.isArray(value)) {
      obj[key] = deepArrayToObject(value);
    } else {
      obj[key] = value;
    }
  }
  return obj;
};

const a = [['a', 1], ['b', 2], ['c', [['d', 4]]]];

const res = deepArrayToObject(a);

console.log(res);

Upvotes: 1

Related Questions