Hi!
I'm creating a warn system and I want to save warns to JSON file. The problem is that when I'm trying to make a new object in something it overwrites.
My code:
const warnObject = JSON.parse(fs.readFileSync('./data/data.json'));
const id = "739176"
const length = Object.keys(warnObject[id]).length + 1
warnObject[id] = {}
warnObject[id][length] = {}
warnObject[id][length]["reason"] = "This is a reason."
warnObject[id][length]["date"] = new Date().toLocaleString();
fs.writeFileSync('./data/data.json', JSON.stringify(warnObject));
And here's my JSON file:
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
So I want to instead of overwriting warn number 2 create new like this
{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}, {"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}
If you want to have multiple warning objects under the id "739176", you would need to format your json file in order to have an array associated to your id, such as :
{
"739176":[
{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}},
{"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}
]
}
So, once you have formatted your file this way, you will be able to get the array referred by the id, and push objects to it like this :
warnObject[id].push({"4":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}});
Related
The name list is supposedly as below:
Rose : 35621548
Jack : 32658495
Lita : 63259547
Seth : 27956431
Cathy: 75821456
Given you have a variable as StudentCode that contains the list above (I think const will do! Like:
const StudentCode = {
[Jack]: [32658495],
[Rose]: [35621548],
[Lita]: [63259547],
[Seth]: [27956431],
[Cathy]:[75821456],
};
)
So here are the questions:
1st: Ho can I define them in URL below:
https://www.mylist.com/student=?StudentCode
So the link for example for Jack will be:
https://www.mylist.com/student=?32658495
The URL is imaginary. Don't click on it please.
2nd: By the way the overall list is above 800 people and I'm planning to save an external .js file to be called within the current code. So tell me about that too. Thanks a million
Given
const StudentCode = {
"Jack": "32658495",
"Rose": "35621548",
"Lita": "63259547",
"Seth": "27956431",
"Cathy": "75821456",
};
You can construct urls like:
const urls = Object.values(StudentCode).map((c) => `https://www.mylist.com?student=${c}`)
// urls: ['https://www.mylist.com?student=32658495', 'https://www.mylist.com?student=35621548', 'https://www.mylist.com?student=63259547', 'https://www.mylist.com?student=27956431', 'https://www.mylist.com?student=75821456']
To get the url for a specific student simply do:
const url = `https://www.mylist.com?student=${StudentCode["Jack"]}`
// url: 'https://www.mylist.com?student=32658495'
Not sure I understand your second question - 800 is a rather low number so will not be any performance issues with it if that is what you are asking?
The properties of the object (after the trailing comma is removed) can be looped through using a for-in loop, (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
This gives references to each key of the array and the value held in that key can be referenced using objectName[key], Thus you will loop through your object using something like:
for (key in StudentCode) {
keyString = key; // e.g = "Jack"
keyValue = StudentCode[key]; // e.g. = 32658495
// build the urls and links
}
to build the urls, string template literals will simplify the process (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) allowing you to substitute values in your string. e.g.:
url = `https://www.mylist.com/student=?${StudentCode[key]`}
Note the use of back ticks and ${} for the substitutions.
Lastly, to build active links, create an element and sets its innerHTML property to markup built using further string template literals:
let link = `<a href=${url}>${keyValue}</a>`
These steps are combined in the working snippet here:
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const studentLinks = [];
for (key in StudentCode) {
let url = `https://www.mylist.com/student=?${StudentCode[key]}`;
console.log(url);
studentLinks.push(`<a href href="url">${key}</a>`)
}
let output= document.createElement('div');
output.innerHTML = studentLinks.join("<br>");
document.body.appendChild(output);
I'm trying to figure out the best way to approach mapping values back and forward as a sort of translation process. The use case is having to process a non SEO friendly attribute code into a nicer format and display that on the frontend, but i also need to be able to process the nice attribute label back into original code so i can use that in my script. In the following example, i'd want to be able to look up myMap to check if a string value exists in the object, and if it does, pull out its corresponding label.
var myString = 'color_attr_code'; // Want to be able to extract 'color' from the map
var myAltString = 'color'; // Want to be able to extract 'color_attr_code'
var myMap = {
'color_attr_code': 'color'
}
Thanks for any help.
You're on the right track, though in modern environments you might use a Map rather than an object, or at least create the object without a prototype so there aren't false matches on toString or valueOf or other things the default object prototype provides.
You'd have two maps, one going each direction, probably best derived from the same source data:
const mappings = [
["color_attr_code", "color"],
["blah_attr_code", "blah"],
// ...
];
const attrToLabel = new Map(mappings);
const labelToAttr = new Map(mappings.map(([key, value]) => [value, key]));
Then you use attrToLabel.get("color_attr_code") to get the corresponding label, and labelToAttr.get("color") to get the corresponding code.
Live Example:
const mappings = [
["color_attr_code", "color"],
["blah_attr_code", "blah"],
// ...
];
const attrToLabel = new Map(mappings);
const labelToAttr = new Map(mappings.map(([key, value]) => [value, key]));
console.log(`Label for "color_attr_code": ${attrToLabel.get("color_attr_code")}`);
console.log(`Code for "color": ${labelToAttr.get("color")}`);
Or in ES5 (although really, in today's world, there's no reason to write ES5 manually — write modern code and transpile with Babel or similar) and objects:
var mappings = [
["color_attr_code", "color"],
["blah_attr_code", "blah"],
// ...
];
var attrToLabel = Object.create(null);
var labelToAttr = Object.create(null);
mappings.forEach(function(mapping) {
var code = mapping[0], label = mapping[1];
attrToLabel[code] = label;
labelToAttr[label] = code;
});
Then you use attrToLabel["color_attr_code"] to get the corresponding label, and labelToAttr["color"] to get the corresponding code.
Of course, all of this assumes there are always just 1:1 mappings, that there aren't (for instance) two codes that both map to the same label.
I use the following code to add new data to firebase.
var postData = {
NSN: NSN,
ProductName: ProductName,
AssociatedContractNumber: AssociatedContractNumber,
ItemQuantity: ItemQuantity,
viewable_by: uid,
};
InventoryID = firebase.database().ref().child('Posts').push().key;
var updates = {};
updates['/Businesses/' + uid + '/Inventory/' + InventoryID] = postData;
what i want to do is to create a list of NSNs in child "NSN" without the uniquely generated post ids. But all the attempt to add just the NSN to child NSN keeps replace the old with the new NSN. so instead of something like 10 different NSNs i only got 1 which is the most recent one added.
I used this code initially
var postNSN = {
NSN: NSN,
};
updates['/Businesses/' + uid + '/National_Stock_Numbers/' + NSN] = postNSN;
the above only replaces the existing number with the new one instead of adding the new one
I also tried this
var NSNref = database.ref('/Businesses/' + uid + '/NSNs/')
NSNref.set({
NSN: NSN,
})
but nothing happens. How can I add a new NSN to child NSNs without the uniquely generated keys?
Just use push()
Say if you had and NSN object like
var NSN = { ... }
firebase.database().ref().child('Posts').push(NSN);
Doing this will always push the item to the end of your NSN array and firebase will take care creating unique key at the time of pushing.
Remember firebase don't know about arrays it only knows about objects.
I have this array stored in versions.js
var cc_versions = [
"2016-01-22",
"2016-01-21",
];
var cs_versions = [
"2016-01-23",
"2016-01-21",
];
I have been trying to figure out a way to write new data to the top of the array inside the javascript file with python. I run a python script on my computer almost every day and I want to update this array when I run it so that I can have a website load the versions. Is it possible to do this? I know I could write to the file, but it would just go to the bottom of the file outside of the array. Also there will be multiple arrays, so I'm trying to find some python script that can interact with a javascript file so I can target specific arrays.
You could also try using Genshi template language. One of the tags there is
<?python ... ?>
for example:
<?python
import json
dateInit = []
selectInit = []
for fi in form_items:
if (fi["type"] == "date"):
dateInit.append(fi["id"])
if "attrs" in fi and "format-select" in fi["attrs"]:
selectInit.append(fi["id"])
if not "attrs" in fi:
fi["attrs"] = {}
jsonDateInit = json.dumps(dateInit)
jsonSelectInit = json.dumps(selectInit)
?>
Your response should contain form_items dictionary processed somewhere on the back-end. Then in javascript you can 'accept' the variables using '$'-sign:
var dateitems = JSON.stringify($jsonDateInit);
var select_items = JSON.stringify($jsonSelectInit);
import json
NEW_VARIABLES = [1, 2, 3]
with open('your/json/file.json') as data_file:
json_data = json.load(data_file)
# insert at the beginning of the list
json_data['cc_version'].insert(0, 'something new')
json_data['cs_version'] = NEW_VARIABLES + json_data['cs_version']
# write to json file after modifying data
with open('your/json/file.json', 'w') as output_file:
json.dump(json_data, output_file)
I ended up using json as suggested in the comments
import json
with open("cc_versions.txt") as data:
json = json.load(data)
dates = json["dates"]
dates.append("2016-01-21")
dates = set(dates)
dates = sorted(dates, key=lambda d: map(int, d.split('-')))
dates = dates[::-1]
import json
with open("cc_versions.txt", "w") as outfile:
json.dump({'dates':dates}, outfile, indent=4)
Using Parse
I have an array of pointers, and I would like to remove an object from that array using only its objectId:
var rawProductObject = Parse.Object.extend("Product");
var product = new rawProductObject();
product.id = productObjectId;
userInventoryQuery = new Parse.Query("Inventory");
userInventoryQuery.equalTo("objectId", userInventory.id);
product.remove("owners", inventoryQuery)
However this does not work. I am not entirely sure about passing a query to the remove method, and not sure how to test it.
Any ideas?