JREAM
JREAM

Reputation: 5931

JavaScript Dynamically Create Object with Multiple Properties

I am trying to dynamically create a chained JS object from an array, does anyone know how I can accomplish this?

UPDATE

I might have value.dog.cat = 'hello', and I'd like to access that variable.

/UPDATE

item = ['dog', 'cat']

How do I dynamically Create:

value['dog']['cat']

Any vanilla JS or jQuery would be cool.

I can't figure this out, because If I do a loop, eg:

new_value = {};
for (var i = 0; i < item.length(); i++) {
  new_value += [item[i]; // This doesn't make sense
}

Upvotes: 1

Views: 1803

Answers (5)

AmmarCSE
AmmarCSE

Reputation: 30557

Use Array.prototype.reduce to create the object or get the value

var itemArray = ['dog', 'cat'];

var itemObject = {};

itemArray.reduce(function(a, b) {
  if (!a[b]) {
    a[b] = {};
  }
  return a[b];
}, itemObject);

console.log(itemObject);

itemObject.dog.cat = 'test';
var value = itemArray.reduce(function(a, b) {
  return a[b];
}, itemObject);

console.log(value);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

Just use Array.prototype.forEach()

The forEach() method executes a provided function once per array element.

function setObject(o, p, v) {
    p.forEach(function (a, i, aa) {
        if (i === aa.length - 1) {
            o[a] = v;
        } else {
            o[a] = o[a] || {};
            o = o[a];
        }
    });
}

var item = ['dog', 'cat'],
    value = {};

setObject(value, item, 'hello') 
document.write(value.dog.cat);
document.write('<pre>' + JSON.stringify(value, 0, 4) + '</pre>');

Upvotes: 0

Harris
Harris

Reputation: 1785

If value is an object, and value.dog is also an object with a property cat, you can indeed access value.dog.cat as value['dog']['cat']. Properties of objects can be accessed as string indexes, and you basically had it right. The only issue I saw in your question was the way in which you assigned properties to new_value in the first place.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Just need to loop. Simple way is with reduce.

var details = {
    dog : {
       cat : "hello world"
    }
};

var item = ['dog', 'cat'];

var value = item.reduce( function (prev, cur) {
                return prev[cur]; //|| {}; Might want to include the commented out part if keys might not be defined
            }, details);

console.log(value);

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

If I have understood the question right then

var new_value = {};
for (var i = 1; i < item.length; i++) 
{
  new_value[item[i-1]] = item[i]; 
}

Upvotes: 1

Related Questions