简体   繁体   中英

Search key in json object based on value

I populate the options of a select input field based on json data I get from a php-script.

This works fine, but I want to show some extra info, based on the selected option . Basically, I'm looking for a way to find the key that goes with the selected option:

 $("#code").html(result[whichkey]["uniquecode"]);

This fiddle hopefully makes my question a bit more clearer.

Any help is much appreciated!

Given that the option element is created with the uniquecode of the object as its value, why do you even need to access the object again? You can just retrieve the value property of the selected option ...?

Assuming this is just because you've oversimplified your example, and the objects within the array do hold other useful data which is not held in the option element itself, then you can use $.grep to filter the array of objects by the selected uniquecode , like this:

 var json = '[{"uniquecode":"b32dez2","name":"John Doe","foo":"bar"},{"uniquecode":"a2df32","name":"Adam Smith","foo":"buzz"}]'; var result = JSON.parse(json); var $sel = $('#names').change(function() { var value = this.value; var obj = $.grep(result, function(e) { return e.uniquecode == value; }); $("#code").html(obj[0].uniquecode + ' / ' + obj[0].foo) });; result.forEach(function(obj) { $('<option value="' + obj.uniquecode + '">' + obj.name + '</option>').appendTo($sel) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="names"></select> <div id="code"></div> 

Note that I added the foo property to the object to show you how to access properties of the object outside of those placed directly on the option element.

Also note that I simplified the code that generates the option elements as well. If you're going to use jQuery once in your project, you may as well use it everywhere.

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