Reputation: 105
I implemented a drop down where the list is coming from a JSON file but the JSON has duplicate values. How can I get the unique values in that dropdown? Here is my code:
$(document).ready(function() {
$.getJSON("data.json",function(obj) {
$.each(obj, function(key, value){
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
});
});
});
my JSON file looks like this:
[{
"name": "abc1",
"date": 1459461600000
}, {
"name": "abc1",
"date": 1459461600000
}, {
"name": "abc1",
"date": 1459461600000
}, {
"name": "syn2",
"date": 1459461600000
}, {
"name": "syn2",
"date": 1458834026000
}];
In the first dropdown now I'm getting 5 values, abc1
3 times and syn2
2 times. I want to get both abc1
and syn2
only once. Please help!
Upvotes: 2
Views: 5651
Reputation: 337666
You could achieve this by storing the names you've already added to the select in an array, and check that array before adding the next name. Something like this:
var obj = [{ "name": "abc1", "date": 1459461600000}, { "name": "abc1", "date": 1459461600000}, { "name": "abc1", "date": 1459461600000}, { "name": "syn2", "date": 145946160000}, { "name": "syn2", "date": 1458834026000}];
var usedNames = [];
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<select id="dropdown1"></select>
You could de-dupe the array of objects, but this seems overkill when your only requirement is to get a single property in one loop.
Upvotes: 6
Reputation: 705
You have to check the obj values for duplicate then append to the select option like this:
$(document).ready(function() {
$.getJSON("data.json",function(obj) {
var duplicate= [];
$.each(obj, function(key, value) {
if (duplicate.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
duplicate.push(value.name);
}
});
});
});
Upvotes: 0