How to increase the number of an object inside an array with an order of id using addEventListener [closed] - javascript

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
I have 6 products in an array. When I want to increase the quantity of the article, it only interprets the first product in the array, even so I press the other buttons of the other products, and it only increases the first article, it only changes me in the first product.
I did a search for the ids to be able to increase the quantity of the item.
I would like to be able to work around the problem to augment the other products in the array.
const productos = [
{
id: 1,
nombre: "Botella de Miel<br>950g",
precio: 5000,
cantidad: 1,
img: "img/bp.png",
},
{
id: 2,
nombre: "Botella de Miel<br>500g",
precio: 3000,
cantidad: 1,
img: "img/Botella_Med.png",
},
{
id: 3,
nombre: "Cuarta de Miel<br>250g",
precio: 2000,
cantidad: 1,
img: "img/Pacha.png",
},
{
id: 4,
nombre: "Frasco de Miel con Panal<br>500g",
precio: 5000,
cantidad: 1,
img: "img/fGra.png",
},
{
id: 5,
nombre: "Frasco de Miel con Panal<br>250g",
precio: 3000,
cantidad: 1,
img: "img/fMediano.png",
},
{
id: 6,
nombre: "Frasco de Miel con Panal<br>140g",
precio: 2000,
cantidad: 1,
img: "img/fPq.png",
}];
const doc = document.getElementById("pMain");
productos.forEach((p) => {
let cta = document.createElement("div");
cta.className = "card";
cta.innerHTML = `
<img src="${p.img}">
<h3>${p.nombre}</h3>
<p>₡ ${p.precio}</p>
<div class="contCa">
<button id="dis${p.id}" class="dismi"> - </button>
<span class="num">${p.cantidad}</span>
<button id="au${p.id}" class="aumentar"> + </button>
</div>
<button class="btnComprar">Añadir al carrito</button>`;
doc.append(cta)
/* Acciones de la cantidad de productos */
const auMas = document.getElementById(`au${p.id}`);
const tProd = document.querySelector(".num");
auMas.addEventListener("click", () => {
tProd.innerText = aumentarProducto(p.id);
})
});
const aumentarProducto = (pId) => {
const iProd = productos.find((i) => i.id === pId);
return iProd.cantidad++;
}
enter image description here

Related

Access JSON parse and save in object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am trying to access certain objects that are inside a parsed JSON and stored inside an object. In this case data.json
var data = {
json: '',
text: '',
welcome: '',
q1: '',
}
let foo = await fetch(spreadsheet);
data.text = await foo.text();
data.json = JSON.parse(data.text.substr(47).slice(0, -2))
data.welcome = data.json.table.rows[2]
console.log(data.welcome)
I don't know how to access each of them to be able to save them in the object I have.
Here is the parse JSON:
{
c: [
null,
{ v: '2. Pagos' },
{
v: '1. Mi pago no concuerda. (Recuerda que el reporte debe estar dentro de la fecha especificada)'
},
{ v: 'Link Formulario' },
{ v: 'https://forms.gle/jBnmFyHCCBePN9Ws5' },
null,
{ v: null }
]
}
If this:
JSON.parse(data.text.substr(47).slice(0, -2))
works fine, this:
console.log(data.json.c[1].v)
should print:
Pagos

delete and modify properties in array inside json object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Given the following JSON:
const myJson = {
id: 8,
active: true,
invoice: "2022/1001",
invoiceDate: "2022-02-02",
clientId: 1,
storeId: 1,
total: 76.95,
itens: [
{
id: 11,
quantity: 2,
price: 12.10,
total: 24.20,
productId: 1,
invoiceId: 8
},
{
id: 12,
quantity: 5,
price: 10.55,
total: 52.75,
productId: 2,
invoiceId: 8
}
]
};
I need a simple way to remove two attributes from the each item inside the 'itens' array, the properties are 'id' and 'invoiceId'. I also need to recalculate the 'total', coz I do not trust totally the source of the information, I rather multiply 'quantity' by 'price' myself.
I've produced this rather naive code:
myJson.itens.forEach(item => {
item.total =
item.quantity *
item.price;
delete item.id;
delete item.invoiceId;
});
And it works rather fine, however, no way that it must be it. Looks too lame and laborious to me. I'm exhausted googling for better ways of doing it.
Can it be done better?
Rather than mutating the original data, you could map it to a new object
const myJson = {"id":8,"active":true,"invoice":"2022/1001","invoiceDate":"2022-02-02","clientId":1,"storeId":1,"total":76.95,"itens":[{"id":11,"quantity":2,"price":12.1,"total":24.2,"productId":1,"invoiceId":8},{"id":12,"quantity":5,"price":10.55,"total":52.75,"productId":2,"invoiceId":8}]}
const newObject = {
...myJson, // keep the rest but map "itens"
itens: myJson.itens.map(({ id, invoiceId, ...iten }) => ({
...iten, // everything except "id" and "invoiceId"
total: iten.quantity * iten.price // recalc total
}))
}
console.log("newObject:", newObject)
.as-console-wrapper { max-height: 100% !important; }

How to edit an Embed Author?

I want to edit the author of an embed sent by my bot.
The message is sent by this code :
task_chan.send('', {
embed: {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
})
To edit the message I've tried :
taken.embeds[0].author.icon_url = util.avatarURL
taken.embeds[0].author.name = util.username
taken.edit(new Discord.RichEmbed(taken.embeds[0]));
taken contain the message to edit and util an user.
And it only change the name…
I don't understand why but author.icon_url is undefined between these two code samples.
I hope you can help me :)
method channel.send return a promise, so you can use .then(msg=> to get a message object.
let testEmbed = {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
}
task_chan.send({embed:testEmbed}).then(msg => {
testEmbed.name = 'LOL'
testEmbed.iconURL = 'SOMEURL'
msg.edit({embed:testEmbed})
})
I would recommend that you use the built-in methods for creating embeds, in my opinion it is more convenient.

How to update an object inside an array inside an object with mongoose?

Let's say I want to update "numberOfUpVotes" where the title is "Een centrale plek voor alle ideeen". I want the new value of "numberOfUpVotes" to be stored in the database. How do I do that?
Right now my code doesn't give an error, but it also doesn't work. This is what I've tried:
Board.findOneAndUpdate(
{"ideas.numberOfUpVotes": 23},
{$set: {"numberOfUpVotes": 2}}, // $set
{new: true},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("hallo");
});
This is my data:
{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: ida1,
userId: id1,
title: 'Een centrale plek voor alle ideeen',
text: 'Een plek waar alle ideeen getoond worden op een scherm ofzo. Waar mensen dan op kunnnen stemmen via hun telefoon',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: ida2,
userId: id1,
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
}
You can do this without mongoose, something like.
const board = {
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: 'ida1 (demo)',
userId: 'id1 (demo)',
title: 'Een centrale plek voor alle ideeen',
text: 'Verkort voor demonstratie',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: 'ida2 (demo)',
userId: 'id1 (demo)',
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
};
// find the filtered record and update its value
// the found record is a reference, so the value
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;
// QED
console.log(JSON.stringify(board, null, " "));
This is my final answer:
Board.update(
{"ideas._id": mongoose.Types.ObjectId("abc123")},
{$inc:{"ideas.$.numberOfUpVotes": 1}},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("succes! (:");
})

Javascript - How to store result of the for loop into the variable?

This the data that I'm trying to parse, especially "text" value from the indexes:
(8) [a, a, a, a, a, a, a, a]
0:a {id: 2, articleId: "1156688772", type: 2, html: "<div id="DIV_1" style="box-sizing:border-box;color…ionUI.enableUserInput() }</script></div></div>", text: "Fyll ut feltene under for å starte en chat: Alle f…tionSession.conversationUI.enableUserInput() }"}
1:a {id: 3, type: 5, date: 1529671597923, html: "", text: ""}
2:a {id: 4, type: 1, html: "hvordan får jeg tak i en sånn bombrikke", text: "hvordan får jeg tak i en sånn bombrikke"}
3:a {id: 5, articleId: "1140973712", type: 2, html: "Gratulerer med ny bil! Velg den avtalen som passer for deg:", persistentOptions: Array(2), …}
4:a {id: 6, type: 1, html: "er det gratis med elbil", text: "er det gratis med elbil"}
5:a {id: 7, articleId: "1158440612", type: 2, html: "<p>El-biler passerer foreløpig gratis i&nbs…g i Norge, hvis man har AUTOPASS-avtale.</p>", text: "El-biler passerer foreløpig gratis i de fleste bomanlegg i Norge, hvis man har AUTOPASS-avtale."}
6:a {id: 8, type: 1, html: "a med dere", text: "a med dere"}
7:a {id: 9, articleId: "1158681852", type: 2, html: "<p>Jeg beklager, jeg forstår ikke spø…. Kan du si det på en annen måte?</p>", text: "Jeg beklager, jeg forstår ikke spørsmålet ditt. Kan du si det på en annen måte?"}
length:8
__proto__
:Array(0)
I am trying to figure it out a best way to store a result of a for loop into variable to pass it to some HTML field. For Example I would like result of this code, which is giving me great results:
var chat = nanorep.floatingWidget.$refs.core.conversationSession.entries
var chatHistory = function() {
for (var i=2; i<chat.length; i++){
console.log(chat[i].text + ' ');
}
}
chatHistory();
to be stored in the: var history = "result of above for loop" variable.
I was trying with the return instead of console.log, but without much success.
Is ran out of ideas, maybe anyone more experienced than me was facing similar issues in the past, and found a way to solve it?
Thanks for any kind of reply in advance.
You could map the values from index 2 and onwards and join each text. Or take the array without joining for later processing.
var chat = nanorep.floatingWidget.$refs.core.conversationSession.entries,
chatHistory = function() {
return chat.slice(2).map(({ text }) => text).join(' ');
};
console.log(chatHistory());

Categories

Resources