JavaScript and Json issue - javascript

[Update]
I Have chosen to go with the database now and make a new collection for each command, it will then collect all the users that use the command.
Does anyone know how I can get multiple arrays in my Json file, I have 3 slash commands on discord that I a trying to collect data from, However when I use to command it just updates the current array in the Json file, I would like to either get all the uses of each command. So that then I can import the Json files to Mongodb.
I am new to JavaScript and using Mongodb so I am still learning so I would really appreciate all the help I can get below I will provide my code samples so you can see if I am doing something wrong.
Example of what I want to achieve
{
"id": "281185483717869569",
"command": "architect",
"name": "UKzs",
"description": [
{
"value": "569",
"name": "x"
},
{
"value": "663",
"name": "y"
},
{
"id": "281185483717869569",
"command": "duke",
"name": "UKzs",
"description": [
{
"value": "123",
"name": "x"
},
{
"value": "123",
"name": "y"
}
]
}
]
}
JavaScipt File
Client.ws.on("INTERACTION_CREATE", async (interaction, msg) => {
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
console.log(args);
const title = {
id: interaction.member.user.id,
command: command,
name: interaction.member.user.username,
description: args,
};
fs.writeFile("title.json", JSON.stringify(title, null, 2), (err) => {
if (err) {
console.log(err);
} else {
console.log("File has been written");
}
});
if (command == "duke") {
const description = args.map((opt) => {
return opt.value;
});
const embed = new Discord.MessageEmbed()
.setTitle(`Would like the duke title!`)
.setColor("RANDOM")
.setDescription(`These are my Coordinates \n ${description}`)
.setTimestamp()
.setAuthor(interaction.member.user.username);
Client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: await createAPIMessage(interaction, embed),
},
});
}
if (command == "architect") {
const description = args.map((opt) => {
return opt.value;
});
const embed = new Discord.MessageEmbed()
.setTitle(`Would like the architect title!`)
.setColor("RANDOM")
.setDescription(`These are my Coordinates \n ${description}`)
.setTimestamp()
.setAuthor(interaction.member.user.username);
Client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: await createAPIMessage(interaction, embed),
},
});
}
if (command == "scientist") {
const description = args.map((opt) => {
return opt.value;
});
const embed = new Discord.MessageEmbed()
.setTitle(`Would like the scientist title!`)
.setColor("RANDOM")
.setDescription(`These are my Coordinates \n ${description}`)
.setTimestamp()
.setAuthor(interaction.member.user.username);
Client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: await createAPIMessage(interaction, embed),
},
});
}
});
Json File
[
{
"id": "281185483717869569",
"command": "architect",
"name": "UKzs",
"description": [
{
"value": "123",
"name": "x"
},
{
"value": "123",
"name": "y"
}
]
}
]
As you can see there is only one input there from the command, If I use another command like /duke then input my data on discord then it will just update the above Json file.
Even better if someone can point me in the right direction on how to get this to save to a database then I would appreciate it, I am not 100% sure on how to do but I think it has something to do with schemas.

My apologies for answering with a question. But does "...how I can get multiple arrays in my Json file..." mean "how can I nest arrays in JSON?" Is what you want to know is how to define a JSON array within another JSON array?
If that's what sought, it's:
[
{
"id": "281185483717869569",
"command": "architect",
"name": "UKzs",
"array-within-array": [1,2,3, ["one", "two", "three"]],
"description": [
{
"value": "123",
"name": "x"
},
{
"value": "123",
"name": "y"
}
]
}
]

Related

How to create a variable from response body in Postman?

I have the following response body:
`
{
"timestamp": "2022-11-08T12:40:11.631Z",
"data": {
"version": "2.2",
"endpoints": [
{
"identifier": "credentials",
"role": "SENDER",
"url": "https://example.com/credentials65"
},
{
"identifier": "tokens",
"role": "RECEIVER",
"url": "https://example.com/tokens245"
},
{
"identifier": "tokens",
"role": "SENDER",
"url": "https://example.com/tokens353"
},
.......
For each identifier and role (in Postman tests session), i want to define variables automatically.
I tried the following for the first ones:
_.each(pm.response.json(), (responseBody) => {
if (responseBody.identifier['data'][1]['identifier'] === "credentials") {
pm.globals.set("credentials_url", responseBody.url)
}
else if (responseBody.identifier === "tariffs") {
pm.globals.set("tariffs_url", responseBody.url)
}
})
The problem is that i do not know how to call the "identifier" and the script do not enter in the if loop. Can anyone help?
const endpoints = pm.response.json().data.endpoints;
for (const endpoint of endpoints) {
const array = pm.globals.get(`${endpoint.identifier}_url`) ?? [];
array.push(endpoint.url);
pm.globals.set(`${endpoint.identifier}_url`, array);
}
You can access the URLs in the arrays by using pm.globals.get("tariffs_url"), pm.globals.get("credentials_url") etc. (it'll work for every identifier)

How to update nested object in mongoose? [duplicate]

This question already has an answer here:
How to update nested object in array (Mongoose/MongoDB)
(1 answer)
Closed 6 months ago.
I'm building a kanban task management app. So far I've been able to create a task and delete task but I can get my head around how to update a nested task object. I have searched the documentation there's no clear explanation.
I wanted to update the task with the id of 62ff74bfe80b11ade2d34455 - req.params.id with the req.body.
{
"_id": "62fa5aa25778ec97bc6ee231",
"user": "62f0eb5ebebd0f236abcaf9d",
"name": "Marketing Plan",
"columns": [
{
"name": "todo",
"_id": "62fa5aa25778ec97bc6ee233",
"tasks": [
{
"title": "Task Four",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
]
},
{
"name": "doing",
"_id": "62fa5aa25778ec97bc6ee234",
"tasks": []
},
{
"name": "done",
"_id": "62fa5aa25778ec97bc6ee235",
"tasks": []
}
],
"__v": 0
}
// #desc Edit task
// #route PUT /api/tasks/:id
// #access Private
const editTask = asyncHandler(async (req, res) => {
const { title, description, subtasks, status } = req.body;
const task = await Board.findOne({ "columns.tasks._id": req.params.id });
const taskStatus = await Board.findOne({
"columns.tasks._id": req.params.id,
"columns._id": status,
});
if (!task) {
res.status(400);
throw new Error("Task not found");
}
// Check for user
if (!req.user) {
res.status(401);
throw new Error("User not found");
}
// Make sure the logged in user matches the task user
if (task.user.toString() !== req.user.id) {
res.status(401);
throw new Error("User not authorized");
}
if (taskStatus) {
const updatedTask = await Board.findOneAndUpdate({
"columns.tasks._id": req.params.id,
});
}
task.columns.map(async (val) => {
// check if tasks id equals the status id in the request body
if (val._id.toString() === status) {
const updatedTask = await Board.findOneAndUpdate(
{
"columns.tasks._id": req.params.id,
},
{ $set: { "columns.$[].tasks": { _id: req.params.id } } },
{ new: true }
);
}
});
});
I had to do something similar recently and I couldn't find a way to update it using mongoose. So I have come up with a workaround.
After doing all your checks
// retrieve the column index you want to update (I assume you have only these 3 columns)
const columnIndex = _.findIndex(task.columns, { name: "todo" });
// retrieve the actual column object
const column = task.columns[columnIndex ];
// get the index of the specific task you want to update
const taskIndex = _.findIndex(column.tasks, { _id: req.params.id });
// manipulate whatever you want here on the specific task by its index
task.columns[columnIndex].tasks[taskIndex]._id = req.params.id
// then finally you need to update the whole columns array
await Board.updateOne({your query here}, {
$set: {
columns: task.columns
}
});
This is actually dirty, but your data is structured in a very difficult way.
I am using lodash in the example. you are free to use JavaScript's array methods

Save a specific variable from a postman array

I have a postman json response and within the array the position of a specific variable changes. Based on my response below i need to write a test to loop through the response the first sighting of optionLabel with value "2 Pax Min".
Save its "id" i.e BBBB in the environment variable
I have tried this
var jsonData = JSON.parse(responseBody);
jsonData[[0].optionSet.options].forEach(function(arroption) {
if (arroption.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(arroption.id));
}
});
My Response
[
{
"id": "",
"date": "2019-08-21",
"optionSet": {
"optionSetLabel": "Options",
"options": [
{
"id": "A",
"optionLabel": "QUAD Rm"
},
{
"id": "AA",
"optionLabel": "QUAD Rm with post Accom"
},
{
"id": "AAA",
"optionLabel": "Rm 3 Pax Min"
},
{
"id": "AAAA",
"optionLabel": "4 Pax Min"
}
]
}
},
{
"id": "",
"date": "2019-08-22",
"optionSet": {
"optionSetLabel": "Options",
"options": [
{
"id": "B",
"optionLabel": "QUAD Rm"
},
{
"id": "BB",
"optionLabel": "QUAD Rm with post Accom"
},
{
"id": "BBB",
"optionLabel": "SGL Rm with post Accom"
},
{
"id": "BBBB",
"optionLabel": "2 Pax Min"
}
]
}
}
]
My end result is i want to save the id "BBBB" in the environment variable
You have a braket problem here jsonData[[0].optionSet.options].
Maybe you wanted to do something like jsonData[0].optionSet.options or jsonData[1].optionSet.options
Here this code should do what you want
for (let data of jsonData) {
for (let option of data.optionSet.options) {
if (option.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(option.id));
}
}
}
Same with forEach rather than for loop
jsonData.forEach(function(data) {
data.optionSet.options.forEach(function(arroption) {
if (arroption.optionLabel === '2 Pax Min') {
pm.environment.set("pax", JSON.stringify(arroption.id));
}
})
})
Mickael's answer should be the accepted solution (I upvoted it) but I just wanted to offer the same thing done with Lodash, which is built-in to Postman.
_.each(pm.response.json(), (data) => {
_.each(data.optionSet.options, (option) => {
if (option.optionLabel === '2 Pax Min') {
pm.environment.set("pax", option.id);
}
})
})
I see lots of answers that do this var jsonData = JSON.parse(responseBody); to parse the response body but it's the same as just using the newer pm.* API function pm.response.json() to do the same thing.
https://learning.getpostman.com/docs/postman/scripts/postman_sandbox_api_reference/

Can't acces my JSON files with ES6

I'm working on a little chat application where you can click on different contacts and see / send messages.
I have this users.json file with the contacts:
{
"results":[
{
"gender":"female",
"name":{
"title":"Ms",
"first":"Leonie",
"last":"Otto"
},
"location":{
"street":"3076 raiffeisenstraße",
"city":"meißen",
"state":"sachsen-anhalt",
"postcode":62480
},
"email":"leonie.otto#example.com",
"login":{
"username":"bigwolf465",
"password":"stephane",
"salt":"Ip5qcgs5",
"md5":"fe5df54750c64b7c5d54c92f0cb91f11",
"sha1":"17d255fb64135b5e247a4ef5554557a1d2a8881e",
"sha256":"341d750fce611b853b4f27d485f10ef9f9c3add4de12a7fbf838a1fd2d5168a9"
},
"dob":"1955-01-08 01:03:55",
"registered":"2012-07-07 16:42:10",
"phone":"0265-7006038",
"cell":"0178-0561111",
"id":{
"name":"",
"value":null
},
"picture":{
"large":"https://randomuser.me/api/portraits/women/8.jpg",
"medium":"https://randomuser.me/api/portraits/med/women/8.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/women/8.jpg"
},
"nat":"DE",
"status": "online"
},
{
"gender":"female",
"name":{
"title":"Miss",
"first":"Olive",
"last":"Wright"
},
"location":{
"street":"2912 manukau road",
"city":"timaru",
"state":"otago",
"postcode":30721
},
"email":"olive.wright#example.com",
"login":{
"username":"brownrabbit413",
"password":"derek",
"salt":"gRxy7hHq",
"md5":"dc214ffe467373790c8500abd1ff0f8f",
"sha1":"7b7847e1a9e3b3de081e3eeebf972dc5d2b5527a",
"sha256":"1763dff5c43e1cea431d1ad8c1648c586af9d1e1410001d743078af143ce30b9"
},
"dob":"1982-07-01 12:12:29",
"registered":"2016-03-25 19:15:33",
"phone":"(003)-127-5232",
"cell":"(133)-307-2001",
"id":{
"name":"",
"value":null
},
"picture":{
"large":"assets/img/users/233899238.jpg"
},
"nat":"NZ",
"status": "online"
}
I both put them in a list item where I show their name, username and profile picture. This all works out well.
The next I want is that if I click on the specific contact, it shows all their message history.
So as an example for the contact with the username bigwolf465 I use this json file:
{
"ok": true,
"messages": [
{
"type": "message",
"user": "me",
"text": "Can I have this?",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "No.",
"ts": "1512085950.218404"
},
{
"type": "message",
"user": "me",
"text": "Ah, perhaps I’ve miscommunicated. I’m asking for it because I want it.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "I understood that, actually.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "me",
"text": "I think maybe you’re not hearing me. I’d like it because I want it.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "There's no problem with my hearing. The problem is that your argument is, as the Romans would say:",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "Circulus in probando.",
"ts": "1512085950.000216"
}
],
"pin_count": 0
}
I also want to make a list item for these messages, but it doens't seem to work out. This is the JS code I have right now:
const handleContactClick = ({
currentTarget: $li
}) => {
loadContactDetails($li);
};
const loadContactDetails = $li => {
fetch(`./assets/data/messages/${$li.dataset.username}.json`)
.then(r => r.json())
.then(parseContactDetail);
}
const parseContactDetail = messages => {
const $container = document.querySelector(`.messages-list`);
const $li = document.createElement(`li`);
$li.classList.add(`reply`);
$container.appendChild($li);
const $img = document.createElement(`img`);
$img.setAttribute(`src`, `assets/img/me.png`);
$li.appendChild($img);
const $p = document.createElement(`p`);
$p.textContent = `${messages.text}`;
$li.appendChild($p);
}
When I click on the specific contact, it just adds messages with the text "undefined". I don't really know how to fix it, it seems I can't get acces to the JSON file.
Here's the function, fixed:
const parseContactDetail = person => {
const $container = document.querySelector(`.messages-list`);
person.messages.forEach(m => {
const $li = document.createElement(`li`);
$li.classList.add(`reply`);
$container.appendChild($li);
const $img = document.createElement(`img`);
$img.setAttribute(`src`, `assets/img/me.png`);
$li.appendChild($img);
const $p = document.createElement(`p`);
$p.textContent = `${m.text}`;
$li.appendChild($p);
});
}
The function now properly grabs .messages from the passed data object, then loops over the array, creating a <li> for each element.

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

Categories

Resources