1

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
}
5
  • 1
    So you want it to be an object all the way through? Commented Dec 9, 2015 at 17:28
  • how should the JSON finally look like? Commented Dec 9, 2015 at 17:28
  • Yes, value is an existing object, which I'd like to turn into value['dog']['cat'] for example, that way it will grab the right property from value. Commented Dec 9, 2015 at 17:29
  • So why don't you include that in the question.... Commented Dec 9, 2015 at 17:31
  • Okay I added an Update Commented Dec 9, 2015 at 17:32

5 Answers 5

2

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);

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

Comments

2

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);

1 Comment

you are possibly overwriting some former properties.
1

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]; 
}

Comments

0

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.

3 Comments

Yes sorry, I wasn't clear -- I want to GET data from the value (JSON), not create new objects if that makes sense?
Oh, so the array provides strings, and the strings correspond to the names of properties in the object?
Yessir, I added an update to try to explain it more clearly :)
0

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>');

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.