简体   繁体   English

基于值在json对象中搜索关键字

[英]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. 我根据从php脚本获得的json数据填充选择输入字段的选项。

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? 鉴于option元素是用对象的uniquecode作为其值创建的,为什么您甚至需要再次访问该对象? You can just retrieve the value property of the selected option ...? 您可以只检索所选optionvalue属性...?

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: 假设这仅仅是因为您简化了示例,并且数组中的对象确实保存了其他有用的数据,而这些数据并未包含在option元素本身中,那么您可以使用$.grep通过选定的uniquecode $.grep来过滤对象数组, 像这样:

 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. 请注意,我在对象中添加了foo属性,以向您展示如何访问直接放置在option元素上的对象之外的对象属性。

Also note that I simplified the code that generates the option elements as well. 还要注意,我也简化了生成option元素的代码。 If you're going to use jQuery once in your project, you may as well use it everywhere. 如果要在项目中一次使用jQuery,则最好在任何地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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