redconservatory
redconservatory

Reputation: 21924

Convert an array to nested object using Lodash, is it possible?

I have an array:

["a", "b", "c", "d"]

I need to convert it to an object, but in this format:

a: {
  b: {
    c: {
      d: 'some value'
    }
  }
}

if var common = ["a", "b", "c", "d"], I tried:

var objTest = _.indexBy(common, function(key) { 
  return key;
 }
);

But this just results in:

[object Object] {
  a: "a",
  b: "b",
  c: "c",
  d: "d"
}

Upvotes: 1

Views: 2147

Answers (1)

Platinum Azure
Platinum Azure

Reputation: 46183

Since you're looking for a single object out of an array, using _.reduce or _.reduceRight is a good candidate for getting the job done. Let's explore that.

In this case, it's going to be hard to work from left to right, because it will require doing recursion to get to the innermost object and then working outward again. So let's try _.reduceRight:

var common = ["a", "b", "c", "d"];
var innerValue = "some value";

_.reduceRight(common, function (memo, arrayValue) {
    // Construct the object to be returned.
    var obj = {};

    // Set the new key (arrayValue being the key name) and value (the object so far, memo):
    obj[arrayValue] = memo;

    // Return the newly-built object.
    return obj;
}, innerValue);

Here's a JSFiddle proving that this works.

Upvotes: 5

Related Questions