How do I overwrite object properties in an array? - javascript

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;
}

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

making JSON from string

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);
}

Keep Javascript constant the same after function is recalled

I am trying to create a dynamic list so when the user performs a search it will repopulate the list. The problem is that I can't seem to make an immutable constant to store the original div content. Every time the function get's called this variable gets reinitialized.
Is there a way to achieve this without using cookies ? Any help is sincerely appreciated. The code is not complete because I couldn't get passed this step but if you think I am totally heading toward the wrong direction please let me know.
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
<script>
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
var newList = '';
var found = false;
function filterPatients(){
var searchQuery = document.getElementById('search');
var query = searchQuery.value;
var listContainer = document.getElementById('patientList');
var patientList = listContainer.getElementsByTagName('li');
for (var i = 0; i < originalList.length; i++){
var link = patientList[i].getElementsByTagName('a');
var link = link[0].text;
/** remove whitespaces for easy comparison **/
link = link.toLowerCase();
query = query.toLowerCase();
link = link.replace(/\s/g, "");
query = query.replace(/\s/g, "");
/** check every character in query **/
if (link.length > query.length && link.substring(0,query.length) == query){
found = true;
newList += '<li>' + patientList[i].innerHTML + '</li>';
}
}
if (found == true){
listContainer.innerHTML = newList;
newList = '';
}
else{
listContainer.innerHTML = "<li>No patient by that name</li>";
}
console.log(frozen);
}
</script>
const originalList = document.getElementById('patientList').getElementsByTagName('li').cloneNode(true);
Make originalList a copy of the element. Currently, you are setting originalList and patientList to be the same list of elements, so changing one will also change the other. Use element.cloneNode(true) to make a deep copy of a DOM element

Losing scope when using array.concat() and .slice() together on jquery object list

I think the code will explain it, but I'm trying to slice a jquery object list into an array and then concatenate them onto another array, multiple times. Anyways in the .each function i am getting elements in the lis variable, but when I try to slice and concat them onto the listItemArray, it isn't working. I assume I'm losing scope or there is some binding issue or something, but I can't figure out what it is. Thanks for the help. Also I know there is a jquery.slice method but I wanted to keep it vanilla if possible.
var updateSection7 = function(desired) {
var section = $('#' + _me.UUID + ' .section7yAxis');
var showedList = section.find('ul:not(:hidden)');
var listItemArray = [];
var _slice = Array.prototype.slice;
showedList.each(function(ind,el){
var lis = $(el).find('.control-group');
if(lis.length>1){
listItemArray.concat(_slice.call(lis));
}
});
}
UPDATED: Here I included both the push and concat varieties of solving the problem and did away with some wasted cpu time per requests.
var updateSection7 = function(desired) {
var lis = $('#' + _me.UUID + ' .section7yAxis ul:not(:hidden) .control-group');
var listItemArray = [];
var concatTester = [];
var _slice = Array.prototype.slice;
var _push = Array.prototype.push;
//these end up doing the same thing
_push.apply(listItemArray, _slice.call(lis));
concatTester = concatTester.concat(_slice.call(lis));
}
concat doesn't mutate the original array. It returns the new array.
Try this:
listItemArray = listItemArray.concat(_slice.call(lis));

Split Javascript String

I've got a javascript string called cookie and it looks like that:
__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en
It could have more ;xxxxxx; but always the entries will be surrounded by ;.
Now i want to split my var into a array and search for the entry "language=xy", this entry should be saved in "newCookie".
Could anyone help me please i'm completly stucked at splitting the var into a array and search for the entry.
Thanks for helping and sharing
var cookie = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;';
var cookie_array = cookie.split(';'); // Create an Array of all cookie values.
// cookie_array[0] = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10'
// cookie_array[1] = '__utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
// cookie_array[2] = '__utmb=43024181.19.10.1349761990'
// cookie_array[3] = '__utmc=43024181'
// cookie_array[4] = 'language=en'
var size = cookie_array.length; // Get Array size to prevent doing lookups in a loop.
for (var i = 0; i < size; i++) {
var keyval = cookie_array[i].split('='); // Split into a key value array
// What we're trying to find now.
// keyval[0] = 'language'
// keyval[1] = 'en'
if (keyval[0] == 'language') { //keyval[0] is left of the '='
//write new cookie value here
console.log('Language is set to ' + keyval[1]); // keyval[1] is right side of '='
}
}
Hope this helps ya out.
For more info on the split() method look at split() Mozilla Developer Network (MDN) documentation
Use a simple regexp for this:
var getLanguage = function(cookie){
var re = new RegExp(/language=([a-zA-Z]+);/);
var m = re.exec(cookie);
return m?m[1]:null;
};
var lang = getLanguage('__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;');
// lang = "en"

Categories