2

I'm not sure if it is possible to achieve such thing through JavaScript so I'm asking for help here.

I have a string:

var value = 'level1.level2.level3';

And I have an object:

var object = {
    level1 : {
        level2 : {
            level3 : 0
        },
    },
}

Is it possible to get a reference to that object using string value, not just value of specific object key. Using a traverse function but a reference so it could be possible to operate with it.

JSFiddle

I've checked and I'm sure this is NOT a duplicate question since in a duplicate version result of parsing function will be object key value, not the object key itself.

1
  • I'm afraid, you will have to write it Commented May 4, 2015 at 10:51

3 Answers 3

5

One liner:

[ob].concat(value.split('.')).reduce(function(a, b) { return a[b] })

Sample:

Object.prototype.getValue = function(path) {
    return [this].concat(path.split('.')).reduce(function(a, b) { return a[b] });
}

// usage:

alert((
{
    level1 : {
        level2 : {
           level3 : 0
        },
    },
}).getValue('level1.level2.level3'));

You cannot change the value of 0 in this way because it will be not an object reference

You need to get level1.level2 object and change its level3 field if you want to affect your original object

ob.getValue('level1.level2').level3 = 25;

- that's how javascript work

However, its possible to write a method to set its value

Object.prototype.setValue = function(path, value) {
    var last = (path = path.split('.')).splice(-1);
    [this].concat(path).reduce(function(a, b) { return a[b] })[last] = value;
}

var ob = {
  level1 : {
     level2 : {
       level3 : 0
     }
  }
};

ob.setValue('level1.level2.level3', 25);

alert(ob.level1.level2.level3);

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

Comments

0
function getValue(object, path) {
    var array = path.split('.');
    var current = object;
    for (var i = 0; i < array.length; i++) {
        current = current[array[i]];
    }
    return current;
}

Use example var x = getValue(object, value);

Comments

0

Although I hate using eval, you can try it if you absolutly sure about value:

var object = {
  level1 : {
     level2 : {
       level3 : 'text'
     }
  }
};

var value = 'level1.level2.level3';

$('.result').text(eval('object.' + value));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='result'></div>

1 Comment

it works, but the performance of eval is very bad!

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.