How to append data to an object with Javascript - javascript

Heres is how I add data to my object:
let trade = [
new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol),
]
The problem is when I run this:
console.log(trade[0].price);
It seems that overwrites my object from the beginning.
I add my class code. How i can print the first data from the object
class RecordStock {
constructor(price, timestamp, stockquantity, tradetype, stocksymbol) {
this.price = price;
this.timestamp = timestamp;
this.stockquantity = stockquantity;
this.tradetype = tradetype;
this.stocksymbol = stocksymbol;
}
static recordTrade(){
console.log(price[0]);
}
}

I think you are looking to push objects into the trade array. You can achieve this by simply appending to the array.
You can push objects with something like this
Assuming you have a function that adds the RecordStock object. Here is how it could be.
let trade = [];
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));
Now you can access the latest RecordStock you pushed using this trade[trade.length - 1]. trade[0] will always contain the object which you pushed first. This is the usual array functionality.

The problem is that inside the function I declare de var every time. I put let trade out of the function

Related

How to add the key of the object to the array in js

I have such objects:
robot {
id
skill
currentWorkPlace
}
warehouse {
aiStaff
currentStatus
boxes
}
I have to write a function that should add the id of a new worker to the aiStaff array, and write a reference to the warehouse object to the job in the currentWorkPlace. But I don't know how not to change the array in the warehouse.('registerRobot' function should not rewrite array 'aiStaff' inside 'warehouse' object) and I don't have to create a new variable
There is my code:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff = [robot.id];
}
I dont know how to not rewrite array 'aiStaff'. Please help me Guys.
It looks like your warehouse.aiStaff is an array. In this case change your function to add the robot ID to the array:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push(robot.id);
}
If I understood correctly you need to 'add' a new robot, but you are having the issue that the entire array gets overridden.
Considering warehouse.aiStaff is an array, if you want to add a new 'worker' you need to push the new item into the array.
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push({
id: robot.id
});
}

Why is my code behaving like I have duplicate keys in a dictionary despite using unique strings? Javascript / Appscript

I am trying to loop through a dictionary of customers and save energy usage data, but for some customers when I try to change the values in their usage dictionary it will also change a completely different customer's value. I have a nested dictionary with customer utility information, the top-level key being a unique internal ID.
I stripped my code down to a single loop, looping through the top-level keys and setting the same month's usage for all customers in the dictionary to be the value of the iterator. After that, as shown in the code sample below, I log the values for three customers. After that, I increment only one of those customer's usage, and log the values again. The console shows that two over the customer's have dictionaries that are tied together somehow, but I can't figure out why or how to solve this. I can't discern any pattern in the keys of the linked customers, either.
Structure of the nested dictionary:
CustDict =
{"N0100000XXXXXX" =
{"name" = "XXXX"},
{"address" = "XXXX"},
{"meter_read_dates" =
{"2021-05-13" =
{"usage" = "XXXX"}
}
}
}
Stripped down code I used to demonstrate what is happening as simply as possible (real ID values):
Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])
custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] =
custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] + 1
Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])
Console Output:
11:54:56 AM Info 346.0
11:54:56 AM Info 346.0
11:54:56 AM Info 322.0
11:54:56 AM Info 347.0
11:54:56 AM Info 347.0
11:54:56 AM Info 322.0
Code used to create the CustDict dictionary:
stmtCR = conn.prepareStatement('SELECT cust_id, utility_account, cycle_id, read_cycle FROM customers')
results = stmtCR.executeQuery()
resultsMetaData = results.getMetaData()
numCols = resultsMetaData.getColumnCount();
results.last();
numRows = results.getRow();
i = 0
results.first()
var custDict = {}
while (i < numRows)
{
custDict[results.getString(1)] = {}
custDict[results.getString(1)]["id"] = results.getString(1)
custDict[results.getString(1)]["utility_account"] = results.getString(2)
custDict[results.getString(1)]["cycle_id"] = results.getString(3)
custDict[results.getString(1)]["read_cycle"] = results.getString(4)
results.next()
i++;
}
for (i = 0; i < Object.keys(custDict).length; i++)
{
tempCust = custDict[Object.keys(custDict)[i]]
tempCycleId = tempCust["cycle_id"]
tempReadCycle = tempCust["read_cycle"]
tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle]
custDict[Object.keys(custDict)[i]] = tempCust
}
cycleIdShdDict is a seperate dictionary that contains a set of dates associated with each cycle_id and read_cycle
I suspect the problem is that Object.keys(custDict) is returning the keys in a different order at different places in the for loop. So you're getting the object from one key, and then assigning it to a different key.
There's no need to assign back to custDict[Object.keys(custDict)[i]] since you're modifying the object in place, not a copy.
But instead of looping through the keys, loop through the values and modify them.
Object.values(custDict).forEach(tempCust => {
let tempCycleId = tempCust["cycle_id"];
let tempReadCycle = tempCust["read_cycle"];
tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle];
});

Function returning object instead of Array, unable to .Map

I'm parsing an order feed to identify duplicate items bought and group them with a quantity for upload. However, when I try to map the resulting array, it's showing [object Object], which makes me think something's converting the return into an object rather than an array.
The function is as follows:
function compressedOrder (original) {
var compressed = [];
// make a copy of the input array
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 1;
var a = new Object();
// loop over every element in the copy and see if it's the same
for (var w = i+1; w < original.length; w++) {
if (original[w] && original[i]) {
if (original[i].sku == original[w].sku) {
// increase amount of times duplicate is found
myCount++;
delete original[w];
}
}
}
if (original[i]) {
a.sku = original[i].sku;
a.price = original[i].price;
a.qtty = myCount;
compressed.push(a);
}
}
return compressed;
}
And the JS code calling that function is:
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
The result is:
contents: [ [Object], [Object], [Object], [Object] ]
When I JSON.stringify() the output, I can see that it's pulling the correct info from the function, but I can't figure out how to get the calling function to pull it as an array that can then be mapped rather than as an object.
The correct output, which sits within a much larger feed that gets uploaded, should look like this:
contents:
[{"id":"sku1","price":17.50,"quantity":2},{"id":"sku2","price":27.30,"quantity":3}]
{It's probably something dead simple and obvious, but I've been breaking my head over this (much larger) programme till 4am this morning, so my head's probably not in the right place}
Turns out the code was correct all along, but I was running into a limitation of the console itself. I was able to verify this by simply working with the hard-coded values, and then querying the nested array separately.
Thanks anyway for your help and input everyone.
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
In the code above the compressedOrder fucntion returns an array of objects where each object has sku, price and qtty attribute.
Further you are using a map on this array and returning an object again which has attributes id, price and quantity.
What do you expect from this.
Not sure what exactly solution you need but I've read your question and the comments, It looks like you need array of arrays as response.
So If I've understood your requirement correctly and you could use lodash then following piece of code might help you:
const _ = require('lodash');
const resp = [{key1:"value1"}, {key2:"value2"}].map(t => _.pairs(t));
console.log(resp);
P.S. It is assumed that compressedOrder response looks like array of objects.

Push a var in an array

Im fairly new to programming. Mostly I can find the solution to my problems online but not this time. I've found serveral posts about pushing a variable into an array, however when I console.log the array to check if the variable is actually in the array, he doesn't return the name of the variable that I want. What I get back is: [Card, Card], and what I want to see is: [card_Fireball, card_Waterbolt, etc]. The code I use is:
var Deck = [];
function Card(name, type, cost, points, damage, heal){
this.name = name;
this.type = type;
this.cost = cost;
this.points = points;
this.damage = damage;
this.heal = heal;
}
var card_Fireball = new Card("Fireball", "spell", 2, 1, 3, 0);
var card_Waterbolt = new Card("Waterbolt", "spell", 2, 1, 3, 0);
Deck.push(card_Fireball);
Deck.push(card_Waterbolt);
console.log(Deck);
The solution is probably fairly simple but I can't figure it out with my beginner experience :P Thanks for the help!!
You are doing everything correct just replace console.log with following:
console.log(JSON.stringify(Deck));
Access the card names with "Deck[x].name", where x is the index of the card in the array Deck.
To get all the names:
for(i=0;i<Deck.length;i++){
console.log(Deck[i].name);
}
Assuming you name all your cards the same way as you did in your example, you could use this to get the variable names:
for(i=0;i<Deck.length;i++){
console.log('card_' + Deck[i].name);
}
If you want to get an array of the variable names you have used, those are lost on the way.
In case you want an array of the names or any other property, try making a new array and pushing every value to it.
var names = [];
Deck.map(function(v) { names.push(v.name) })
console.log(names);
Output:
["Fireball", "Waterbolt"]

Create an array of specific elements from another array?

I have an array that can't be changed in terms of the element positions:
var array = ['item1', 'section1', 'section2', 'section3', 'section4', 'section5', 'prod1', 'prod2']
I want to make a new array from 'array' that takes the elements from position 1 - 5 (so all the section elements). It needs to be by position as the section elements make change by name.
var array2=array.slice(1,6)
See here for more information.
let's say we have an array like this
const FILES_WITH_10_ASSETS = [
'../assets/uploads/Desktop-300x600.jpeg',
'../assets/uploads/Desktop-728x90.png',
'../assets/uploads/Mobile-160x600.jpeg',
'../assets/uploads/Mobile-300X50.jpeg',
'../assets/uploads/Mobile-320x50.jpeg',
'../assets/uploads/Mobile-320x480.jpeg',
'../assets/uploads/Mobile-1024x768.jpeg',
'../assets/uploads/Tablet-300x250.jpeg',
'../assets/uploads/Tablet-Interstitial-320x480.gif',
'../assets/uploads/Tablet-Interstitial-320x480.jpeg'
];
now we want some specific items from an array, we will create a function for this, here I have stored the function in an constant for further use
const SELECT_ASSETS = function(assetName: string) {
let filtered_assets: string[] = [];
for (let i in FILES_WITH_10_ASSETS) {
if (FILES_WITH_10_ASSETS[i].includes(assetName) === true) {
filtered_assets.push(FILES_WITH_10_ASSETS[i]);
}
}
return filtered_assets;
};
and we call the method like this in our file
const ASSETS_NAME = SELECT_ASSETS(ASSET_NAME);
now we can pass the assets name to any function or method, if we pass the ASSET_NAME as Tablet we will get all three tablet paths, or if we change it to Mobile, we will get all five Mobile paths

Categories

Resources