2

my problem is that i have a json-object with and array into here an example.

var object = {
 'items':['entry1','entry2']
}

I want to access 'entry2' over a constant string that I receive and shouldn't be changed.

var string = 'items[1]';

The only way I'm solving this problem is over the eval function...

eval('object.'+string);

This returns me entry2.

Is there any other way to achieve this without using eval()? Like object[string] or object.string

2
  • What are the possible values of string ? Commented Sep 4, 2013 at 11:24
  • in this case 'items[0]' or 'items[1]' Commented Sep 4, 2013 at 11:45

4 Answers 4

3

Supposing your string is always the same form, you could extract its parts using a regex :

var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];

Explanation :

The regex builds two groups :

(\w+) : a string
\[(\d+)\] : some digits between brackets

and those groups are at index 1 and 2 of the array returned by match.

+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.

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

2 Comments

this is the solution but I seem not to understand it correctly. Anyway it works and I have to check how the method is working. Thx :)
yeah, I've also found the method on google and it helped alot. Thx :)
1

On top of dystroy's anwser, you can use this function:

function getValueFromObject(object, key) {
  var m = key.match(/(\w+)\[(\d+)\]/);
  return object[m[1]][+m[2]];
}

Example:

var object = {
 'items':['entry1','entry2']
}

var string = 'items[1]';

var value = getValueFromObject(object, string); //=> "entry2"

1 Comment

Does this really add something to my answer ?
0

First, you can get the array from inside:

var entries = object.items // entries now is ['entry1','entry2']

Then you need to index that to get the second item (in position 1). So you achieve what you want with:

var answer = entries[1] // answer is now 'entry2'

Of course, you can combine this to get both done in one step:

var answer = object.items[1] // answer is now 'entry2'

... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s

1 Comment

it was just for the understanding ;) but I honor your advice
-1

try something like this

  object.items[1];

2 Comments

this isnt possible since items[1] is received as a string... that's my problem...
as I told before items[1] is received as a string from an request so it's not static code. It's a string = 'items[1]'

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.