2

Lets say I've got a JavaScript array like this:

var arr=['first','second','third'];

And a value like this:

var val='bacon';

How can I make it so the array and value get translated into an object like this:

var obj[first][second][third]='bacon';

Two Important Catches:

1) The number of elements in the array is always different. So it could just be ['first','second'] or ['first','second','third','fourth'] etc...

2) obj will already exist and needs to not be overwritten with the new value. For example obj[first][somethingelse]='eggs' may already exist, and still needs to exist after obj[first][second][third]='bacon' is added.

I've tried to come up with various loops and recursive functions to do this. But the variable number of elements in the array keeps tripping me up.

1
  • so what if there are two arrays [first][second][third] ? is this possible ? And show some code atleast. Commented Aug 27, 2015 at 14:24

2 Answers 2

3

Use array.reduce to simplify the process:

var object = {a: true}, value = 'bacon'; 

['first','second','third'].reduce(function(a, b, index, array) {
  return a[b] = index === array.length - 1 ? value : (a[b] || {});
}, object);

console.log(object);

This takes the initial object and every time returns a new object assigned to a particular property name (if there was no object like that before). As long as object is just a reference, the new created object is set as your object property, and the same object is returned as a parameter a. When it reaches the last element in the array, the value is returned instead of a new object.

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

5 Comments

Fails the obj[first][somethingelse]='eggs' test - you overwrite existing objects. codepen.io/anon/pen/YyKZZj
Fixed if you replace value : {} with value : (a[b] || {})
exactly what I was going to do... Thank you for the comments. At first I was thinking it needs to override, did not pay enough attention. My bad
well just a test to show it is not empty. Could be whatever
This is absolutely amazing! Thank you for being part of humanity @smnbbrv
0

do you mean something like this???

$(document).ready(function(){
    var arr=['first','second','third'];
    var myObj = {};
    for(item in arr) {
        myObj[arr[item]] = 'test-'+item
    }

        console.log(myObj)
});

http://jsfiddle.net/leojavier/mw4hm5ma/4/

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.