Accessing object values with generic method - javascript

I'm doing some refactoring and trying to create a generic method which is able to populate given dropdowns with object data. However I'm coming up against an issue regarding how to make accessing different object data generic. For example:
Original method
function populateDropdown(element, data) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].ID + '>' + data[i].Name + '</option>');
}
This works if a given array of objects has the field ID and Name. What I'm trying to achieve is something like this
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].valueField + '>' + data[i].dataField + '</option>');
}
When I've tried calling this method like this I get Undefined as a result: populateDropdown($('#myDropdown'), dataArray, "ID", "DataType");
And when I've tried without the "" I get a console error saying that ID and DataType isn't defined. Is there a way to tell my method what fields I want from the object?

Use bracket notation -
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Note - to make this a little more resilient to special characters in the property values, I would do this instead:
$('<option />', { value : data[i][valueField] }).text(data[i][dataField]).appendTo(element);

You can do data[i][valueField]and data[i][dataField]:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}

Use bracket notation [] to access the properties:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}

What the others said, not sure if this is helpful, just fyi you can also define default values if you don't pass them like so...
function populateDropdown(element, data, valueField, dataField) {
valueField = valueField || 'some_default_value';
dataField = dataField || 'some_default_value';
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Then you can call it like this, leaving valueField and dataField params out:
populateDropdown('someElement', 'someValue');

Related

Don't write comma after last element in for loop

I have function that gets data from a database and displays it in the view:
function GetUsers() {
let url = "/Home/GetUsers";
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
console.dir(data);
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
}
});
}
It displays it with comma, but after the last Username+RoleName it adds a
comma too. As I understood I need to get last iteration of for loop? How I can fix this problem?
I usually make a little trick for this cases:
var separator = "";
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append(separator + '<b>' + data[i].UserName + "-" + data[i].RoleName + '</b>');
separator = ",";
}
Simply check if the current element is the last element and if so, don't add the comma:
$('#taskresult3').append('<b>'+ data[i].UserName +"-"+ data[i].RoleName + (i === data.length - 1 ? "" : ",")+'</b>');
Dont add comma for the last element.
for (var i = 0; i < data.length; ++i) {
if (i === data.length - 1)
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName '</b>');
else
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
There is one more approach using .join() on arrays
var _html = [];
for (var i = 0; i < data.length; ++i) {
var _inhtml = '<b>' + data[i].UserName + "-" + data[i].RoleName+'</b>';
_html.push(_inhtml);
}
$('#taskresult3').append(_inhtml.join(","));
With this you can cut down the overhead of manipulating DOM multiple times.
You could use map and join to solve this, instead of using a loop.
$('#taskresult3').append('<b>' + data.map(item => item.UserName + "-" + item.RoleName).join(',</b><b>') + '</b>')
map would convert the array, to an array of item.UserName + "-" + item.RoleName, this array then would be joined together using ,</b><b> and the last part that is then missing is the first <b> and the last </b>
You can avoid the comma and improve your logic by building the HTML in an array, then using join() to display it, like this:
success: function(data) {
var html = data.map(function(item) {
return data[i].UserName + ' - ' + data[i].RoleName;
});
$('#taskresult3').append(html.join(',');
}
Also, keep in mind the semantic use of the <b> tag:
However, you should not use <b> for styling text; instead, you should use the CSS font-weight property to create boldface text.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b
I'd suggest placing the HTML you append within a container that has font-weight: bold applied to it through CSS.

How to dynamically access object's property?

I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.
What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.
function getTempDev(devNumTemp, devNumHum, id, description){
$.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
var array = result.Device_Num_42.states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
$("#id").html(description + "<div class='right'>" + array[i].value + "°C" + " (" + someVariable + "%" + ")" + "<br></div>");
}
}
};
objectFindByKey(array, 'service', 'something');
});
};
You can acces to object's properties like this
var array = result["Device_Num_" + devNumTemp].states;
It's considered a good practice to test for field's existance before trying to access it:
var array = [];
if (result && result["Device_Num_" + devNumTemp]){
array = result["Device_Num_" + devNumTemp].states;
}
This way we prevent Null Pointer Exception type errors.

How to add option/ ListItem to dropdownlist dynamically

I need to build my DDL dynamically,I get info from DB using JSON (I get the data with no problem) but couldn't show my data in my DDL...
I tried three different ways, nothing changed.. What am I doing wrong ?
//HTML
<asp:DropDownList ID="productDDL" runat="server" CssClass="ddl"></asp:DropDownList>
//Javascript
function creatDDL(data) {
var obj = $.parseJSON(data.Data);
for (var i = 0; i < obj.length; i++) {
$("#productDDL").append("<option>" + obj[i].id + "' - '" + obj[i].name + "</option>");
$("#productDDL").append("<option>"+obj[i].id + "' - '" + obj[i].name+"</option>");
$("#productDDL").append($("<option></option>").html(obj[i].id + "' - '" + obj[i].name));
}
}
I like your third attempt best. Assuming your data is in order, you just need to brush up on the jQuery API.
Here's a working version of what I gather you're trying to do:
function createDDL(data) {
var options = $.parseJSON(data.Data);
$.each(options, function(n, option) {
var $option = $('<option />').text(option.name).val(option.id);
$("#productDDL").append($option);
});
}
Fiddle: http://jsfiddle.net/klenwell/Esr5q/

How to dynamically access values in a json with jquery

Yes there are a number of threads questioning similar issues to the following, but I found very few and very little help regarding dynamic keys and pulling single values from jsons holding multiple values per key.
I have a json in which the keys are dynamic and I need to be able to call upon each separate value.
Any ideas?
json example below:
{"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}}
I have played around with the following code, but currently only managed to spit out a string of values rather than individual ones:
$.each(data, function (key1, value1) {
$.each(value1, function (key, value) {
$('body').append('<li id="' + key + '">' + key1 +' ' + key +' ' + value + '</li>');
});
});
Solved with this:
json = JSON.parse(data);
for (var index in json) {
$.each(json[index], function(key,value) {
for(var i = 0; i< json[index][key].length; i++){
$('body').append('<li>' + index +' ' + key +' ' + json[index][key][i] + '</li>');
}
});
}
JSON returns an object in JavaScript. So you could do something like this:
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
console.log("id"+i+": "+json.AppliedPrepaidBundle.id[i]);
}
This prints out all the values of the ID object: 14, 15, 24, 25, etc
Use JSON.parse to create an object. (See How to parse JSON in JavaScript). Then loop through the properties with for (x in yourObject) { ... }.
var jsonObject = JSON.parse('your JSON-String');
for (property in jsonObject) {
// do something with jsonObject[property]
console.log(property + ' ' + jsonObject[property]);
}
you can work with the javascript basic functionality:
http://jsfiddle.net/taUng/
var data = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var dataIndex in data) {
console.log(dataIndex, data[dataIndex]);
var subData = data[dataIndex];
for (var subDataIndex in subData) {
console.log(subDataIndex, subData[subDataIndex]);
}
}
And so on...
When your a fit in javascript you can also work with Recursion to don't repeat yourself. (http://en.wikipedia.org/wiki/Dont_repeat_yourself)
From this example you can access all elements
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
$('body').append("<li>AppliedPrepaidBundle id"+i+": "+json.AppliedPrepaidBundle.id[i]+'</li>');
}
for (var i=0; i<json.AppliedPrepaidBundle.prepaid_bundle_id.length; i++) {
$('body').append("<li>PrepaidBundleid"+i+":"+json.AppliedPrepaidBundle.prepaid_bundle_id[i]+'</li>');
}
for (var i=0; i<json.Device.id.length; i++) {
$('body').append("<li>Device id"+i+": "+json.Device.id[i]+'</li>');
}
Here is the fiddle

JQueryUI selectmenu - How to add more options

Through javascript how can I add more options to a dropdown selectmenu?
Currently trying the following with no luck:
for (i = 0; i < json.powerDropDownItems.length; i++) {
//$('#powerSelect').append($("<option></option>").attr("value", json.powerDropDownItems[i]).text(json.powerDropDownItems[i]));
$('#powerSelect').selectmenu("value", "nice name");
//$('#powerSelect').appendTo("<option>" + json.powerDropDownItems[i] + "</option>");
}
$('#powerSelect').selectmenu("refresh");​
UPDATE
Thanks to naveen, I got it working (also added code to clear the list). Here is my following code:
service.getPowerDropDowns(productEC, $('#mountSelect').val(), function (response) {
var json = $.parseJSON(response.value);
var options = [];
// Clear the options first
$("#powerSelect option").each(function(index, option) {
$(option).remove();
});
options.push("<option value=''>Choose</option>");
for (i = 0; i < json.powerDropDownItems.length; i ++)
{
options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
}
$('#powerSelect').append(options.join("")).selectmenu();
$('#powerSelect').selectmenu('enable');
});
This will work
$(function() {
var options = [];
for (i = 0; i < json.powerDropDownItems.length; i++) {
options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
}
//append after populating all options
$('#powerSelect')
.append(options.join(""))
.selectmenu();
});​
Demo: http://jsfiddle.net/codovations/p863Q/
Depends on the version.
https://github.com/jquery/jquery-ui/tree/selectmenu uses refresh method
https://github.com/fnagel/jquery-ui/tree/selectmenu uses selectmenu() like naveen described.

Categories

Resources