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.
Related
I am working on a script in which i need some data based on a lot of timestamps.
Below is just an example
var timestampData1 = [1555486016,1555486017,1555486018...];
var timestampData2 = [1555486016,1555486017,1555486018...];
var data = [];
data[1] = [];
$.each(timestampData1,function(index,value) {
data[1][value] = 1;
});
data[2] = [];
$.each(timestampData2,function(index,value) {
data[2][value] = 1;
});
console.log(data);
The example above will output the following in the console
However if i examine the data in the console, i see a lot of empty sets counting from 0 up to the very last timestamp
So my question is:
Will javascript set all of these indexes, or is it simply an indication in the console?
If not, i guess that it is very bad for performance, doing it like above ?
Yes your assumption is correct. If you use objects which have key/value pairs whis won't be a problem, however you will you array methods like push and filter.
Example:
var timestampData1 = [1555486016,1555486017,1555486018...];
var timestampData2 = [1555486016,1555486017,1555486018...];
var data = [];
//Make data[1] an object not array
data[1] = {};
$.each(timestampData1,function(index,value) {
data[1][value] = 1;
});
//Make data[1] an object not array
data[2] = {};
$.each(timestampData2,function(index,value) {
data[2][value] = 1;
});
console.log(data);
Output:
I have Json Parse list which need to push each category list.
example :
listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
var values = [];
for(var i=0;i<listChartPeriods.length;i++){
categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date
values.push(listChartPeriods[i])
}
expected out put:
categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]
values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values
Just use Object.keys to get the dates in the array.
const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);
Below should get the job done for you. A for in loop is your friend when it comes to working with objects.
var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
for(var char in listChartPeriods){
for(var i = 0; i < listChartPeriods[char].length; i++){
categoryData.push(listChartPeriods[char][i]);
}
}
console.log(categoryData);
EDIT: Just read your updated question and you are only wanting the key names. You can also do this with a for in loop.
for(var char in listChartPeriods){
categoryData.push(char)
}
console.log(categoryData);
Following the solution:
for (let date in listChartPeriods){
categoryData.push(date);
let [first] = listChartPeriods[date];
values.push(first);
}
categoryData = ["2018-05-04", "2018-05-11", "2018-05-18", "2018-05-25", "2018-06-01"]
values = [21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442]
I have an array of data like so:
var data = [
["Acid", 0.741593940836, 0.45657115],
["Cannabis", 0.94183423, 0.31475],
["LSD", 0.1367547, 0.936115]
];
Which plots points to a scatterplot.
I also have other arrays of data that look like this - the arrays are declared with the same names of each sub array in data. These arrays are then stored in an array:
var Acid = ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"];
var collection = [Acid, Cannabis, LSD];
I'm trying to create some code returns one (two or all) of the arrays (Acid, Cannabis, LSD) based on a selection of the points in the scatterplot. The code I have so far is as below - it should be noted that the selecting points is done via Lasso, I've included that code also.
var lasso_end = function() {
lasso.items()
.classed("not_possible",false)
.classed("possible",false);
var selected = lasso.selectedItems()
.classed("selected", true)
.attr("r", 13);
var selectedPoints = [];
selected.data().forEach((arr) => {
arr.forEach((d) => {
selectedPoints.push(d);
});
});
for(var i = 0; i < selectedPoints.length; i++) {
for(var j = 0; j < collection.length; j++) {
if(selectedPoints[0] == collection[j]) {
console.log(collection[j]);
}
}
}
Just to reiterate, I'm trying log data from Arrays Acid, Cannabis, and LSD to the console, if points in the array data is selected
In response to one of the comments, I've put a console.log() after selectedPoints and this is the output and format:
Ok, so if I understand correctly, after doing
selected.data().forEach((arr) => {
arr.forEach((d) => {
selectedPoints.push(d);
});
});
your selectedPoints array logs out as
"Acid",
0.123123,
0.123131,
"Cannabis"
0.232222,
0.221121... etc.
and then you want to console.log the arrays whose names are in the above output, here the arrays Acid and Cannabis.
The issue is that you create the array collection with named variables holding the word arrays: the names of the variables that held the arrays don't transfer, you can't do
var foo = 2
var array = [foo]
and the try to access the value with array[foo], that's not how JS arrays work. They only have numerical indices.
You should use an object:
var collection = {
Acid: ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"]
}
and then extraxt the names from selectedPoints
var pointNames = selectedPoints.filter(x => typeof x === "string")
and the loop through the pointNames array, logging out the corresponding property on the object collection if it exists. Here's a simplified snippet:
var data = [
["Acid", 0.741593940836, 0.45657115],
["Cannabis", 0.94183423, 0.31475],
["LSD", 0.1367547, 0.936115]
];
var selectedPoints = ['Acid', 0.741593940836, 0.45657115];
var collection = {
Acid: ["leak","advice", "draft","addition","genuine","object","advance","freshman","sour","say","page","old","loot","white","soul","wriggle","agony","sensitivity","laundry","format"]
}
var pointNames = selectedPoints.filter(x => typeof x === "string")
pointNames.forEach(point => {
if(collection[point]) {
console.log(collection[point])
}
})
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'm trying to create a summary report for a order based on products in the order
However my summary array is always empty.
var summary = [];
_.each(this.products, function(product,counter) {
var invoice = {};
invoice.total = 0;
invoice.dealer_discount = 0;
invoice.program_discount = 0;
invoice.adjusted_total = 0;
_.each(product.materials, function(material) {
_.each(material.variants, function(variant) {
var difference = 0;
invoice.total = parseFloat(invoice.total + variant.price.msrp);
if(variant.price.discount_type === 'dealer') {
difference = parseFloat(variant.price.msrp - variant.price.discount_price);
invoice.dealer_discount = parseFloat(invoice.dealer_discount + difference);
} else {
difference = parseFloat(variant.price.msrp - variant.price.discount_price);
invoice.program_discount = parseFloat(invoice.program_discount + difference);
}
});
});
// This never seems to get populated?
// If I set the array key to counter like summary[counter] it works fine but I need:
summary[product.fulfilled_by] = invoice;
});
It is probably something simple that I'm doing wrong.
Any help is appreicated.
Just changing the first line will solve your problem
var summary = {}; // Object
An Object store items in key : value fashion, while an Array will just contain value which can be accessed by an index which is numeric and hence worked when you put summary[counter].