1

Lets say I have an following object:

var obj = {
    property: [{key:"value1"},{key:"value2"}]
}

And I have following string property[0].key

How can I obtain value2 using this string inside code?

Basicly I want to de something like this obj["property[1].key"]

If string have only dots, I can use following code:

function get_property_by_string(object, string){
    return string.split(".").reduce(function(obj, key) {
        return obj[key];
    }, object);
}

But with array this code doesn't work. Any suggestions?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Grisha
  • 77
  • 1
  • 1
  • 7

3 Answers3

2

Use can use the Eval() function which takes a string content and evaluate it as a command.

http://www.w3schools.com/jsref/jsref_eval.asp

Tomer W
  • 3,395
  • 2
  • 29
  • 44
  • Is it any chance to avoid eval? Or is it only easy way? – Grisha Jul 29 '13 at 08:11
  • I guess you are concerned of Code injections? Can you specify your Goal, and constraints , maybe we can suggest an alternative way... – Tomer W Jul 29 '13 at 08:14
  • 1
    the other way is to parse the string... not that hard to do... but will take about 25 lines of code – Tomer W Jul 29 '13 at 08:16
0

The fact that your property is stored as a string is not an issue. access the property of an object as such:

var obj = { 'key_a' : [{key:'value', otherkey: 'other value' }] },
    property = "key_a";

 obj[property][0].otherkey; // outputs "other value"

Avoid eval() if you can, it will only add overhead to your program and its usage is considered bad practice by some.

jdog
  • 174
  • 6
  • the problem is that I don't know where is exactly this property located. I have only string. – Grisha Jul 29 '13 at 08:22
  • You don't need to know where the property of an Object is located, you access it via its key (a string), but perhaps I have misunderstood the question? :) – jdog Jul 29 '13 at 08:25
0

You're creating 'property' as an array, so you should be able to access it directly. I've tested the following code locally on Chrome and it appears to work fine.

var obj = {
    property: [{key:"value1"},{key:"value2"}]
}

function test()
{
    alert(obj.property[0].key); // shows value1
    alert(obj.property[1].key); // shows value2
}
Jeff
  • 126
  • 3