简体   繁体   中英

Use string variable to access value of object

I have a text input.

I want the user to be able to fill out a value in that text input like some of these examples:

  • results[0].address_components[0].long_name
  • results[0].formatted_address
  • fo.o[0].bar (where fo.o is a single key)
  • etc. (pretty much literally anything)

Then I want to take that value and use it as a key on some parsed JSON. So like...

$.parseJSON('data.json').results[0].address_components[0].long_name would return something like San Francisco .

How can I do this?

If I save the input value as a variable, say selector , and then try $.parseJSON('data.json')[selector] it just comes back undefined.

If I try to regex the selector and convert all instances of [ into . and remove all ] and split at . then reduce, then selectors like fo.o (one key) will break...

Thanks in advance!

You should generally set the results of parseJSON to a variable, rather than parse it every time you access it. parseJSON is generally going to go down to C code (depending on the environment), but it will still be really inefficient to call it over and over.

var res = $.parseJSON('data.json');

From there, you can access it like you would any other JavaScript object:

res.results , which is identical to res["results"] (which, in your case appears to be some kind of array).

A string key with special characters ( . , - , and pretty much anything non a-zA-Z0-9) is always accessed via the second form: res["fo.o"] .

Note that this chains, so you can access res["fo.o"]["bar"] exactly as you'd address res["fo.o"].bar .

I would recommend using a JavaScript library like lodash for this (if this is feasible in your project, otherwise looking at its implementation might help):

It provides a large set of utility functions. The get function does exactly what you are looking for, namely it resolves a path on an object.

Sample code (assuming _ is your lodash reference):

var path = 'results[0].address_components[0].long_name'; // the user input
var data = $.parse('data.json');
var result = _.get(data, path); // resolves the path on the data object

As for the fo.o property name, I doubt there would be an easy solution, as this essentially makes your syntax ambiguous. How would you distinguish between a property fo.o and fo ?

use eval . You would put everything as a string. So just concatenate strings based on the input. Then eval it. for example:

var str = "$.parseJSON('data.json').results[0].address_components[0].long_name";

and then eval it at runtime.

var result = eval(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM