I'm trying to push the first and last initial of a user to an object array of my users contact information using angular.forEach and I'm not doing it right.
Here is the code I have:
var firstInit = '';
var lastInit = '';
angular.forEach(self.contacts, function(value, key){
firstInit = key.first_name.charAt(0);
lastInit = key.last_name.charAt(0);
this.push(firstInit + ':' + lastInit);
});
But I'm getting TypeError: Cannot read property 'charAt' of undefined
Any advice?
Update:
I changed the code to the following and now I can get the values, but when I try to push onto the contacts object, I'm getting "push" is not a function. Though if I take away the "key" I can push the initials, but they are on the root of the array and not where I want them to be in each object.
Here is the code:
var firstInit = '';
var lastInit = '';
angular.forEach(self.contacts, function(value, key){
firstInit = self.contacts[key].first_name.charAt(0);
lastInit = self.contacts[key].last_name.charAt(0);
self.contacts[key].push(firstInit + lastInit);
});
Either key.first_name or key.last_name is undefined in your contacts somewhere. This is a possible solution:
var firstInit = '';
var lastInit = '';
angular.forEach(self.contacts, function(value, key){
if (key.first_name)
firstInit = key.first_name.charAt(0);
if (key.last_name)
lastInit = key.last_name.charAt(0);
this.push(firstInit + ':' + lastInit);
});
Here's the fix:
var inits = '';
var newContacts = [];
angular.forEach(self.contacts, function(value, key){
console.log(value.first_name);
inits = self.contacts[key].first_name.charAt(0) + self.contacts[key].last_name.charAt(0);
value.userInitials = inits;
newContacts.push(value);
});
Alternatively, I could have just used "value" instead of getting the index/key. That got me the name fields. I created a new object array and pushed the value. I added the new key/value pair with dot notation.
Related
Currently code is as given below,
var child_tids = [];
$('.term-selection').each(function(index){
var field = $(this).attr('field');
child_tids.push($(this).val());
});
I need to segregate it based on the attribute 'field'
So I tried the below
var child_tids = [];
$('.term-selection').each(function(index){
var field = $(this).attr('field');
child_tids[field].push($(this).val());
});
But it gives me the error in console "Cannot Read property push of undefined, how can I implement it?
child_tids would need to be an object, and then create an array for each field you can try:
var child_tids = {};
$('.term-selection').each(function(index){
var field = $(this).attr('field');
if (!child_tids[field]) child_tids[field] = [];
child_tids[field].push($(this).val());
});
What you need is an object and not an array. Use something like:
var child_tids = {};
$('.term-selection').each(function(index) {
var field = $(this).attr('field');
if (typeof child_tids[field] != "object") child_tids[field] = [];
child_tids[field].push($(this).val());
});
I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}
I have some url and I need to replace some parts of it with user input from input type="text" and move to new link with button click.
How can I place variables in URL ?
//some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4
i have function, but it place input at the end of url.
function redirect() {
var baseUrl = 'http://google.com.ua/';
document.myform.action=baseUrl + document.getElementById('url').value;
}
<form name="myform" method="post" onsubmit="redirect()">
<input type="text" id="url">
<input type="submit" value="submit">
</form>
You could build out manual query string parsers and constructors, an example would be like:
function parseQuery(qstr){
var query = {};
var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
for (var i in a) { //iterate the array of values
var b = a[i].split('='); //separate the key and value pair
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
}
return query; //returned the parsed query string object
}
function buildQuery(obj){
var str = [];
for(var p in obj) //iterate the query object
if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into the string array
}
return str.join("&"); //take the array of key value pairs and join them on &
}
Then below we take the string that you gave, for example:
var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';
Now we call the parseQuery function on our string.
var obj = parseQuery($str);
Then we iterate the object which was produced from our parseQuery function
Object.keys(obj).forEach(function(k, i) {
switch(k){
case 't1':
obj[k] = 'replacedt1';
break;
case 'service':
obj[k] = 'replacedServices';
break;
case 'host':
obj[k] = 'replacedHost';
}
});
Now the obj variable has the newly updated values. We can rebuild the query using our buildQuery function by passing the object in.
console.log(buildQuery(obj));
Which will produce something like:
createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4
As usual, the jsFiddle
You can use the new URL object (for older browsers, there is a polyfill) :
var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");
alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/
Played with JavaScript a bit, I believe this solves your problem: http://jsfiddle.net/dk48vwz7/
var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";
//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;
//the query string starts with ?, we remove it.
//then, split it by & symbol
var queryvars = anchor.search.replace(/^\?/, '').split('&');
//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
var queryvar = queryvars[i].split('=');
querycontent[queryvar[0]] = queryvar[1];
}
//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need
//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
var fragment = key;
if (querycontent[key]) {
fragment += "=" + querycontent[key];
}
querymerged.push(fragment);
}
anchor.search = querymerged.join("&")
//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;
EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/
I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}