我有json数组,我想从json数组中获取每个唯一值
JSON数组
'[{"capacity":"4Seater","carname":"car1","price":"83"},
{"capacity":"4Seater","carname":"i10","price":"83"},
{"capacity":"4Seater","carname":"i20","price":"83"},
{"capacity":"8Seater","carname":"car3","price":"83"}]'
我已经试过了
的HTML
<select id="select1"></select>
jQuery代码
$(document).ready(function(){
var jsonstirn = '[{"capacity":"4Seater","carname":"car1","price":"83"},{"capacity":"4Seater","carname":"i10","price":"83"},{"capacity":"4Seater","carname":"i20","price":"83"},{"capacity":"8Seater","carname":"car3","price":"83"}]';
var jsonarray = JSON.parse(jsonstirn);
var capacity_val = ''
$.each(jsonarray,function(i,item){
capacity_val+='<option value="'+item.capacity+'">'+item.capacity+'</option>';
});
$('#select1').html(capacity_val);
});
我不知道该怎么办。我仍然在寻找解决方案。
我正在寻找的输出
<select id="select1">
<option value="4Seater">4Seater</option>
<option value="8Seater">8Seater</option>
</select>
最佳答案
试试这个。
您可以使用.map()
$(document).ready(function(){
var jsonstirn = '[{"capacity":"4Seater","carname":"car1","price":"83"},{"capacity":"4Seater","carname":"i10","price":"83"},{"capacity":"4Seater","carname":"i20","price":"83"},{"capacity":"8Seater","carname":"car3","price":"83"}]';
var jsonarray = JSON.parse(jsonstirn);
var capacity_array = jsonarray.map(function(obj) { return obj.capacity; });
capacity_array = capacity_array.filter(function(v,i) { return capacity_array.indexOf(v) == i; });
var capacity_val = '';
$.each(capacity_array,function(i,item){
capacity_val+='<option value="'+item+'">'+item+'</option>';
})
$('#select1').html(capacity_val);
});
关于jquery - 如何从json数组中获取唯一值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37023243/