After adding JSON data to an html option selector, how can I reference other data when selected?

jquery html json

29 观看


142 作者的声誉

I'm not sure of the proper terminology here so let me show my code:

var json = "";

$.getJSON(json,function(data) {
    for (var x = 0; x < data.length; x++) {

            '<option value="' + data[x].name + '">' + data[x].name + '</option>'

The JSON Data looks like the following but has much more data:

    "id": "test1", 
    "name": "test1", 
    "symbol": "t1", 
    "rank": "1", 
    "price_usd": "55"
    "id": "test2", 
    "name": "test2", 
    "symbol": "t2", 
    "rank": "2", 
    "price_usd": "155"

Essentially when someone uses the select option and choses "test1" I want to display the other information, such as; id, symbol, rank, etc.. What's the best way to go about this dynamically and not write a bunch of if statements?

作者: user3330820 的来源 发布者: 2017 年 12 月 27 日

回应 (2)


1773 作者的声誉

put the resulting JSON string into an object using [JSON.parse]1. Then you can use .toggle() or a couple of other jQuery fun functions and address the applicable item in the object and the values to go with.

作者: NappingRabbit 发布者: 27.12.2017 05:42


12256 作者的声誉


To get all the data in the object which you're using to populate the options (data[x].name),
you can either filter the array of objects or change the structure so you can reference it by name,

here are some examples.

Filtering the array:

var dataXName = 'whatever name'
var obj = data.filter(function(x){ return === dataXName })[0]

Mapping an object:

var byName = data.reduce(function(ac, x){
   return Object.assign(ac, {[]:x}) 
// then you can reference the object with byName['whatever name']

the solutions above are plain js and don't depend on jquery.

作者: maioman 发布者: 27.12.2017 05:51