2

I have the following array:

["recordList", "userList", "lastChanged"]

And I want something like this:

lastChangedValue = "231231443234";        

var object = {};

object = {
   recordList: {
       userList: {
         lastChanged: lastChangedValue 
      }
   }
}

How I can do this? Thanks in advance.

2
  • Is the nesting consistent? Commented Feb 29, 2016 at 20:44
  • So you want each array item to be an object containing the keys beneath it as keys? Commented Feb 29, 2016 at 20:49

4 Answers 4

2

Try this:

var array = ["recordList", "userList", "lastChanged"];


var value = "231231443234";        

function arrayToObject(array, object, value) {
  var ref = object;
  for (var i=0; i<array.length-1; ++i) {
    if (!ref[array[i]]) {
        ref[array[i]] = {};
    }
    ref = ref[array[i]]
  }
  ref[array[array.length-1]] = value;
  return object;
}
alert(JSON.stringify(arrayToObject(array, {}, value)));

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

Comments

1

You can iterate through property names and create one nested level of new object in each iteration:

var props = ["recordList", "userList", "lastChanged"];
var lastChangedValue = "231231443234";

var obj = {}
var nested = obj;
props.forEach(function(o, i) {
    nested[o] = i === props.length - 1 ? lastChangedValue : {};
    nested = nested[o];
});

console.log(obj);

Comments

1

There are probably a bunch of ways to do it, one way is with reduce

var keys = ["recordList", "userList", "lastChanged"];
var temp = keys.slice().reverse(),
    lastChangedValue = "231231443234";  
var result = temp.reduce( function (obj, val, ind, arr) {
  if (ind===0) {
    obj[val] = lastChangedValue;
    return obj;
  } else {
    var x = {};
    x[val] = obj;
    return x;
  }
}, {});
console.log(result);

1 Comment

Keep in mind that reduce was introduced in IE10 and is not supported in IE9 or below.
1

Solving with recursion

var fields = ["recordList", "userList", "lastChanged"];
lastChangedValue = "231231443234";
var object = {};

(function addFields(o, i, v) {
    if (i == fields.length - 1) {
        o[fields[i]] = v;
        return;
    }
    o[fields[i]] = {};
    addFields(o[fields[i]], ++i, v)
})(object, 0, lastChangedValue);


alert(JSON.stringify(object));

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.