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={};
}
Related
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.
My apologies if my question doesn't make sense, and I will try to explain it better...I have an on object and in this object I have an array of objects. I am trying to update one of the found objects in the array of objects, I update the found object but it doesn't update the original object in the array, right now I have this
let vendeeCatalogs = workingVendorImplementorInfo.SVendorCatalogImplementorInfo; // This the array of objects
if (vendeeCatalogs.length > 0) {
for (let i = 0; i < vendeeCatalogs.length; i++) {
foundCatalog = workingVendorImplementorInfo.SVendorCatalogImplementorInfo.find(function (x) { return x.CatalogID == vendeeCatalogs[i].CatalogID });
if (foundCatalog) {
foundCatalog.CatalogGenerationGUID = vendeeCatalogs[i].CatalogGenerationGUID;
foundCatalog.BeginEffectiveDate = vendeeCatalogs[i].BeginEffectiveDate;
foundCatalog.EndEffectiveDate = vendeeCatalogs[i].EndEffectiveDate;
foundCatalog.Multiplier = vendeeCatalogs[i].Multiplier;
foundCatalog.Discount = vendeeCatalogs[i].Discount;
foundCatalog.UOMPrecisionTypeID = vendeeCatalogs[i].UOMPrecisionTypeID;
foundCatalog.IsSelected = vendeeCatalogs[i].IsSelected;
}
}
}
I can see that this is wrong because all it does is updates the foundCatalog, and not the original object that was found.
So how do I find the object and update that object so that the changes are saved in the workingVendorImplementorInfo.SVendorCatalogImplementorInfo?
Why are you not using findIndex() in place of find ?
If you have the index you can then just do something like
vendeeCatalogs[x].CatalogGenerationGUID = ...
I'm trying loop through a large chunk of data and dynamically create a new hashed object with the value being a new array with multiple objects in the array.
let hash = {};
data.map(x => {
hash[x.DateOut] = new Array();
return hash[x.DateOut].push(x);
});
or
for (let i = 0; i < data.length; i++) {
hash[data[i].DateOut] = []; // Or new Array()
hash[data[i].DateOut].push(data[i]);
}
I want to avoid declaring each key:value pair individually as it's a large chunk of data, and I want to avoid making multiple for loops if at all possible.
Thanks for the help.
A fast version checks if the hash exists and take a variable for the key.
var key, object;
for (object of data) {
key = object.DateOut;
if (!hash[key]) hash[key] = [];
hash[key].push(object);
}
If it's just about the initial creating of the array and afterwards pushing you can use this code:
for (obj of data) {
hash[obj.DateOut] = hash[obj.DateOut] || [];
hash[obj.DateOut].push(obj);
}
Example: https://codepen.io/auskennfuchs/pen/aeWdKY
The fastest way without creating a single variable inside loop could be:
let hash = {};
for (let i = 0; i < data.length; i++) {
if (!hash[data[i].DateOut]) {
hash[data[i].DateOut] = [data[i]];
}
else {
hash[data[i].DateOut] = [...hash[data[i].DateOut], data[i]];
}
}
Hope this helps :)
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;
}
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.