I want to create an object by iterating through another one, and essentially appending to that new object.
So the issue at the moment is that the loop finishes with the final value of desiredData = JSON.parse(row[i]["Results"]) being added to the object i times. We should have i different objects added.
That is scoreObjectToSend[desiredUserId] contains the same object for all desiredUserId's.
I've tried using promises and some other JavaScript methods but to no use.
What I require is a loop over users, that adds their data to an object Object.
let raceData = {};
let desiredData = {};
let actualRaceString = raceArray[raceIndex]; // raceIndex defined earlier
let numberOfUsers = row.length; // row defined earlier
let i;
for (i = 0; i < numberOfUsers; i++) {
let desiredUserId = row[i]["Usernames"];
let desiredData = JSON.parse(row[i]["Results"]);
raceData[actualRaceString] = desiredData;
scoreObjectToSend[desiredUserId] = raceData;
}
Related
I'm passing a string which looks something like: "John.Doe.100.Newbie-David.Miller.250.Veteran-" to the SplitDatabase function which splits the string appropriately and assigns the values to the UserDataEntry object. The UserDataEntry object is then pushed in to the global UserData array which is supposed to store all the user data.
For some reason though, the UserData.push(UserDataEntry) part seems to be overwriting previous data in the UserData array. The alert in the 1st loop shows the correct data as it loops, but alert in the second loop at the bottom just shows the last record over and over again.
I'm not sure why this is?
var UserData = [];
function SplitDatabase(result) {
var RawUsers = result.split('-');
var UserDataEntry = {};
for (var i = 0; i < (RawUsers.length - 1); i++) {
var tempUserData = RawUsers[i].split('.');
for (var x = 0; x < (tempUserData.length); x++) {
switch (x) {
case 0:
UserDataEntry.firstname = tempUserData[x];
break;
case 1:
UserDataEntry.lastname = tempUserData[x];
break;
case 2:
UserDataEntry.points = tempUserData[x];
break;
case 3:
UserDataEntry.rank = tempUserData[x];
UserData.push(UserDataEntry);
alert(UserData[i].firstname);
break;
}
}
}
for (var i = 0; i < (UserData.length); i++) {
alert(UserData[i].firstname);
}
}
Calling push will not copy your object, because JavaScript Objects are passed by reference: you're pushing the same Object as every array entry.
You can fix this easily by moving the var UserDataEntry = {}; inside the loop body, so that a new object is created each loop iteration:
for (var x = 0; x < (tempUserData.length); x++) {
var UserDataEntry = {};
Put your line var UserDataEntry = {} inside the for loop.
Right now, you only have one object, and you're setting each part of the array to that object. You overwrite the members in your loop.
If you create a new object inside the loop, you'll add all new members in to the array.
The code below is supposed to decompose a json object sent from Postman into smaller objects that will be stored in a array. The problem is that if I console.log the result, I do see each and every objects decomposed as expected but the array.push method only push the last element of the inner array :
app.post('/commande',async(req,res)=>{
if( await authentification(req.query.login, req.query.pass)){
var data = req.body.data; // array containing json object to be posted
var dataLength = data.length;
var bigObj= []; //array to store objects
for (var i = 0; i<dataLength; i++) {
var orderLines = data[i].orderLines;//array of orders
var info ={};// object unit
info.CptClient = data[i].clientAccount;
info.customerOrderNumber= data[i].customerOrderNumber;
info.orderLabel = data[i].orderLabel;
var shipTo = data[i].shipTo;
info.recepientName = shipTo.recepientName;
info.contactName = shipTo.contactName;
info.ad1 = shipTo.ad1;
info.ad2 = shipTo.ad2;
info.ad3 = shipTo.ad3;
info.postalCode = shipTo.postalCode;
//"etc..."
//
for (var j = 0; j<orderLines.length;j++) {
info.itemRef = orderLines[j].itemRef;
info.itemQty = orderLines[j].itemQty;
info.unitPrice = orderLines[j].unitPrice;
console.log(info);//displays unique orderLabel : ABC01 ABC02 ABC03 XYZ01 XYZ02 XYZ03
bigObj.push(info); // stores only last of each type : ABC03 ABC03 ABC03 XYZ03 XYZ03 XYZ03
}
}
res.json(bigObj)
}else {
res.send("not authorized");
}
})
As explained in the comments, the console.log displays the right information as the objects are being created but the push method somehow would only push the last element of the orderLines array. Is there somebody to explain this phenomenon? Any idea? Thank you.
I'm inserting a list of email recipient with same subject and message but different recipients.
I've already tried some method shown below, it get's the number of recipients to be sent, but it for the recipient it only get's the last recipient pushed into the array, that's why it was sent to the same recipient 3 times.
var emailsObj = [];
var addEmailObj = [], obj;
for (i=0 ; i<rowData.length; i++) {
addEmailObj["claimNo"] = $('#motorClaimNoInfo').val().trim().toUpperCase();
addEmailObj["fileNo"] = $('#motorClaimNoInfo').attr('fileNo');
addEmailObj["claimDate"] = $('#motorClaimNoInfo').attr('claimDate');
addEmailObj["senderCd"] = $('#motorClaimFileComposeEmailFrom').attr('username');
addEmailObj["sender"] = $('#motorClaimFileComposeEmailFrom').val();
addEmailObj["senderEmail"] = $('#motorClaimFileComposeEmailFrom').attr('userEmail');
addEmailObj["recipientCd"] = rowData[i].username;
addEmailObj["recipient"] = rowData[i].userFullName;
addEmailObj["recipientEmail"] = rowData[i].userEmail;
addEmailObj["subject"] = $('#motorClaimFileComposeEmailSubj').val().trim().toUpperCase();
addEmailObj["message"] = $('#motorClaimFileComposeEmailMsg').val().trim().toUpperCase();
emailObj.push(addEmailObj[i]);
emailsObj.push(rowData[i].username);
}
Here's the console for this code
```[INFO ] 2019-05-06 14:25:37.766 [http-nio-8080-exec-10] MotorClaimInquiryController - emailObj {claimNo=100161002000351, fileNo=1, claimDate=11-21-2016, senderCd=MGSIMBIL, sender=MICHELLE G. SIMBILLO, senderEmail=MGSIMBILLO#MAPFREINSULAR.COM, recipientCd=ABSERNIO, recipient=SERNIO, ANNABEL BENAS, recipientEmail=ABSERNIO#MAPFREINSULAR.COM, subject=100161002000351-01, message=}
[INFO ] 2019-05-06 14:25:39.059 [http-nio-8080-exec-10] MotorClaimInquiryController - emailObj {claimNo=100161002000351, fileNo=1, claimDate=11-21-2016, senderCd=MGSIMBIL, sender=MICHELLE G. SIMBILLO, senderEmail=MGSIMBILLO#MAPFREINSULAR.COM, recipientCd=ABSERNIO, recipient=SERNIO, ANNABEL BENAS, recipientEmail=ABSERNIO#MAPFREINSULAR.COM, subject=100161002000351-01, message=}
[INFO ] 2019-05-06 14:25:40.578 [http-nio-8080-exec-10] MotorClaimInquiryController - emailObj {claimNo=100161002000351, fileNo=1, claimDate=11-21-2016, senderCd=MGSIMBIL, sender=MICHELLE G. SIMBILLO, senderEmail=MGSIMBILLO#MAPFREINSULAR.COM, recipientCd=ABSERNIO, recipient=SERNIO, ANNABEL BENAS, recipientEmail=ABSERNIO#MAPFREINSULAR.COM, subject=100161002000351-01, message=}
The result should have different recipients. Thanks
You're only assigning to addEmailObj once:
var addEmailObj = []
This means that every time you mutate or push addEmailObj, you're mutating or pushing the same object. Create it inside the array instead:
for (let i=0 ; i<rowData.length; i++) {
const addEmailObj = {};
Note that since you're not using it as an array, you shouldn't define it as an array - just define it as a plain object, with {}, not []. (Also, best not to implicitly create global variables - declare your i properly) If at all possible, also declare your variables with ES6 syntax (let and const) rather than ES5 syntax to avoid the confusion that can arise from var's hoisting. (var has function scope, not block scope)
// let emailsObj = [];
let addEmailObj = [];
for (i=0 ; i<rowData.length; i++) {
let new_user = {
'claimNo':$('#motorClaimNoInfo').val().trim().toUpperCase(),
'fileNo':$('#motorClaimNoInfo').attr('fileNo'),
'claimDate':$('#motorClaimNoInfo').attr('claimDate'),
'senderCd':$('#motorClaimFileComposeEmailFrom').attr('username'),
'sender':$('#motorClaimFileComposeEmailFrom').val(),
'senderEmail':$('#motorClaimFileComposeEmailFrom').attr('userEmail'),
'recipientCd':rowData[i].username,
'recipient':rowData[i].userFullName,
'recipientEmail':rowData[i].userEmail,
'subject':$('#motorClaimFileComposeEmailSubj').val().trim().toUpperCase(),
'message':$('#motorClaimFileComposeEmailMsg').val().trim().toUpperCase()
};
addEmailObj.push(new_user);
// emailsObj.push(rowData[i].username);
}**
>
Currently, I have an empty new object and I want to populate values from an existing object to new object because I want to use an object with only limited properties from the existing object (e.g. I only want the four properties instead of eight).
Here's how I am doing the mapping so far:
const newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(newObject);
}
So far, it looks to be storing the values from the existing object to newObject. However, it is only saving the last object values and not the different values from the object. How can I fix this to save all values (not just the last values for every object in the array)?
You need to make a copy of that before pushing in array
const newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(Object.assign({}, newObject));
// Or
// this.updatedProducts.push({ ...newObjec });
}
Or Simply create object inside loop. I love to use Array.prototype.forEach and Array.prototype.map
this.updatedProducts = this.PRODUCT_DATA.map(({_productSkuKey, _price, _isActive})=> ({
_productSkuKey,
_storeKey: this.itemPriceForm.get('location').value,
_price,
_status: _isActive
});
Avoid declaring newObject as 'const'. This is an updated code that works for me.
//avoid using a const, as you cannot override it
let newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(newObject);
//after pushing the object, empty all the current contents
newObject={};
}
I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.