如何从json数组中获取唯一值

时间:2016-05-04 09:09:49

标签: jquery json

我有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>

3 个答案:

答案 0 :(得分:1)

您可以合并SetSpread operatorArray#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);

  //Set will hold unique set of elements.
  var uniqueCapacity = 
        [...new Set(jsonarray.map(v => v.capacity))]
          .map(v => '<option value="'+v+'">'+v+'</option>').join("");
 //Map the unique set of elements with required string values.

  $('#select1').html(uniqueCapacity );
});

DEMO

答案 1 :(得分:1)

试试这个。

你可以使用.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);
});

答案 2 :(得分:0)

从广义上讲,如果你想要容量属性的唯一性,你可以尝试

var uniquesVals= [];

$.each(jsonstirn, function(index, value) {
    if ($.inArray(value.capacity, uniquesVals) === -1) {
        uniquesVals.push(value.capacity);
    }
});