I want to display JSON data keys in html dropdown (not values) - javascript

https://api.myjson.com/bins/7xq2x this is my JSON data I want to display the keys in dropdown. My JSON data will be dynamic so I want code for dynamic JSON data to take only the keys
function renderBusinessUnitChart(){
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
Keys: name, abbreviation - this should display in dropdown.

For displaying keys:
function renderBusinessUnitChart(){
var ddown = document.querySelector('#dropdown') // I don't know what kind of dropdown do you have, so we will use regular select
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
const itemKeys = Object.keys(result[0]) // getting keys from first item of result array
var options = itemKeys.map(key => { // looping the keys
const option = new Option(
key,
key
) // creating a one option item for dropdown
ddown.appendChild(option) // adding option to dropdown
return option // returning option and adding it to array
})
console.log (options) // aray of options you will need it for some reason
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
For displaying keys where objects can contain different keys:
function renderBusinessUnitChart(){
// I don't know what kind of dropdown do you have, so we will use regular select
var ddown = document.querySelector('#dropdown')
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result) {
result = [ // for testng purposes only, to check that result may contain objects with different keys
{"name":"Alberta","abbreviation":"AB"},
{"name2":"British Columbia","abbreviation2":"BC"}
]
const options = result // getting array of unique keys from every item in result
.reduce((ac, item) => [...ac, ...Object.keys(item).filter(key => !~ac.indexOf(key))], [])
.map(key => { // looping the keys
// creating a one option item for dropdown
const option = new Option(key, key)
// adding option to dropdown
ddown.appendChild(option)
// returning option and adding it to array
return option
})
// aray of options you will need it for some reason
console.log (options)
}
})
}
$(document).ready(function(){
renderBusinessUnitChart()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
For displaying values:
function renderBusinessUnitChart(){
var ddown = document.querySelector('#dropdown') // I don't know what kind of dropdown do you have, so we will use regular select
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
var options = result.map(_ => { // looping the result
const option = new Option(
_.name,
_.abbreviation
) // creating a one option item for dropdown
ddown.appendChild(option) // adding option to dropdown
return option // returning option and adding it to array
})
console.log (options) // aray of options you will need it for some reason
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>

You can use Object.keys(inputObject) method to get an array of inputObject keys.
So in your case:
// Need to make sure your result is an object instead of array;
var resultObj = Array.isArray(result) ? result[0] : result;
function populateOptions(resultObj){
return Object.keys(resultObj).map(key => {
return `<option value="${key}">${key}</option>`
}).join("");
}
var selectHtml = `<select>${populateOptions(resultObj)}</select>`
See more:
Array.prototype.map()
Array.prototype.join()
Template literal (it's the (``) syntax)
Object.keys()

Related

Populate items from an array into different options tag

I am trying to load some usernames returned via ajax into a dropdown menu using jQuery. The results are successfully getting into the dropdown menu but all the data is getting into just one option tag. I want the data to be in different option tags.
Currently the dropdown menu looks like this
Name1,Name2,Name3,Name4
But I want as:
Name1
Name2
Name3
Name4
Dropdown where I am putting the results:
<div class="form-group">
<select name="name" class="form-control" id="employee_select">
</select>
</div>
jQuery:
//send value via GET to URL
var get_request = $.ajax({
type: 'GET',
url: '/users',
data: {User:User}
});
// handle response
get_request.done(function(data){
// Data returned
dataReturned = data;
// Log data
console.log($.type(dataReturned)); // response is string in the form of
// Name1
// Name2
// Convert to an array
dataArray = [dataReturned]
// Create a new array
newArray = [];
// Populate newArray with items
for(i=0;i<dataArray.length;i++){
if(typeof(dataArray[i])=='string'){
newArray.push(dataArray[i])
}
}
//console.log(newArray);
console.log($.type(newArray)); // an array is returned in the form of ["Name1,Name2,Name3,Name4"]
// Loop through newArray
$.each(newArray, function( index, value) {
$('#employee_select').append("<option>"+ value + "</option>");
})
Thank you.
There's probably a more elegant way of doing this but...
What if you pushed each result into an array and then ran a for loop through each item in array checking to see if each item is a string. The successful results of that, you push into a final array.
for(i=0;i<array.length;i++){
if(typeof(array[i])=='string'){
newArray.push(array[i])
}
}

Set values on Select2 search form for multiselect

I have a json string that I wish to add to select2 multiselect search input. I am getting map error as below
Cannot read property 'map' of undefined
The json field from console log is
[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]
And the js code is
var employees = $(this).attr('data-employees');
console.log(employees);
$("select[name='employees[]']").val(employees.data.map(function(x) {
return x.id; })); // Set the selected data before show it.
$('select').select2()
HTML
<select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select>
As I can see you are getting this array from element attribute and if you are, probably the console.log is a string so, try this:
var employees = JSON.parse( $(this).attr('data-employees') );
console.log(employees);
$('select').select2(); // init with select2
$("select[name='employees[]']").val(employees.map(function(x) {
return x.id; // Set the selected data before show it.
}))
.trigger("change");
If you see this
var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]');
console.log('The whole array:', employees); // you have a valid array
var ids = employees.map(function(x){ return x.id; })
console.log('Employee ids only: ', ids);
Edited

How to get JSON Data depending on other data values in JavaScript

My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})

how to access an objects element based on its name

I have an observable array that I am capturing from the controller , its bringing out out the whole object when I use ko.mapping from js , how can I access an array element from the objects . At the moment it returns somethings"{"driverId":1,"driverName":"Simon Jenkins",}" how do I pick out just the name and not the ID or vice versa
if (!pageViewModel.isAuthenticated()) return;
$.when(getSecureData("/api/vehicleDrivers/" + id))
.done(function (driverList) {
driverList.unshift({ "driverId": 0, "driverName": "Please select a driver..." });
pageViewModel.DriverVM.driverList(driverList);
pageViewModel.vehicleVM.driverDetail.driverId(ko.mapping.fromJS(driverList));
/*var List = driverList;
List[0] = pageViewModel.VehicleVM.driverDetail.driverId;
List[1] = pageViewModel.vehicleVM.driverDetail.driverName;*/
})
.fail(function (message) {
$.msgbox(message);
});
}
If you want to ignore some properties when mapping, you can use the ignore option. If you want to specify which fields are included, you can preprocess with ko.utils.arrayMap
var driverIdList = ko.utils.arrayMap(driverList, function (item) {
return item.driverID;
});
Then you could use ko.mapping to convert that to observables, or just pass it to an observableArray.

display specific object values in an array instead of individually?

I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator

Categories

Resources