1

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"
}

1 Answer 1

5

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.

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

2 Comments

Although the TO asked explictely for lodash, it is worth noting, that JS could do it ootB: jsfiddle.net/7j6zrmqm/1 ;) +1 anyways for the good answer.
ES5 isn't always a viable option, unfortunately.

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.