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

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());

Related

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

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

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.

Filtering out objects in an array of objects without any null values

I'm trying to filter out api output _that doesn't include any null values - the api output (JSON) looks like so:
[{ title:
'Bayern Munich defenders are scared of damned talented Jadon Sancho, says Borussia Dortmund team-mate Axel Witsel - Goal',
date: '2019-08-04T11:42:00Z',
image: null,
description:
'As Leeds kick off the new season with hopes of returning to the Premier League, we remember their painful demise from 15 years ago',
link:
'https://www.goal.com/en/news/even-bayern-defenders-are-scared-of-damned-talented-sancho/huf85pn3ob4s1r0fcjq52nsqe' },
{ title:
'Manchester City y Liverpool se enfrentan con la Community Shield en juego: hora y TV - infobae',
date: '2019-08-04T11:36:59Z',
image:
'https://www.infobae.com/new-resizer/ZvS6Vs3f7Qa_11HIibSiMy8DOUw=/1200x0/filters:quality(100)/s3.amazonaws.com/arc-wordpress-client-uploads/infobae-wp/wp-content/uploads/2019/08/04082112/Guardiola-Klopp.jpg',
description:
'El campeón y el subcampeón de la Premier League se enfrentan con el primer título de la temporada en juego. En la previa, hubo un duelo verbal entre Pep Guardiola y Jürgen Klopp. A las 11, por ESPN2',
link:
'https://www.infobae.com/america/deportes/futbol-europeo/2019/08/04/manchester-city-vs-liverpool-community-shield-2019/' },
{ title:
'Ireland\'s Hourihane bangs in two stunning free-kicks ahead of Villa\'s Premier League return - The42',
date: '2019-08-04T11:33:00Z',
image:
'https://img2.thejournal.ie/article/4752619/river/?height=400&version=4752623',
description: null,
link:
'https://www.the42.ie/conor-hourihane-free-kicks-leipzig-4752619-Aug2019/' } ]
The code I currently has achieves this, but it's so bulky and uses a lot of conditionals - which I'd like to avoid. Can something like this be achieved?
let filteredArr = [];
for (let i = 0; i < data.length; i++) {
if (data[i].title !== null &&
data[i].date !== null &&
data[i].image !== null &&
data[i].description !== null &&
data[i].link !== null) {
filteredArr.push(data[i])
}
}
The output would be like so:
[{ title:
'Manchester City y Liverpool se enfrentan con la Community Shield en juego: hora y TV - infobae',
date: '2019-08-04T11:36:59Z',
image:
'https://www.infobae.com/new-resizer/ZvS6Vs3f7Qa_11HIibSiMy8DOUw=/1200x0/filters:quality(100)/s3.amazonaws.com/arc-wordpress-client-uploads/infobae-wp/wp-content/uploads/2019/08/04082112/Guardiola-Klopp.jpg',
description:
'El campeón y el subcampeón de la Premier League se enfrentan con el primer título de la temporada en juego. En la previa, hubo un duelo verbal entre Pep Guardiola y Jürgen Klopp. A las 11, por ESPN2',
link:
'https://www.infobae.com/america/deportes/futbol-europeo/2019/08/04/manchester-city-vs-liverpool-community-shield-2019/' } ]
You could filter the array by checking all values.
var data = [{ title: 'Bayern Munich defenders are scared of damned talented Jadon Sancho, says Borussia Dortmund team-mate Axel Witsel - Goal', date: '2019-08-04T11:42:00Z', image: null, description: 'As Leeds kick off the new season with hopes of returning to the Premier League, we remember their painful demise from 15 years ago', link: 'https://www.goal.com/en/news/even-bayern-defenders-are-scared-of-damned-talented-sancho/huf85pn3ob4s1r0fcjq52nsqe' }, { title: 'Manchester City y Liverpool se enfrentan con la Community Shield en juego: hora y TV - infobae', date: '2019-08-04T11:36:59Z', image: 'https://www.infobae.com/new-resizer/ZvS6Vs3f7Qa_11HIibSiMy8DOUw=/1200x0/filters:quality(100)/s3.amazonaws.com/arc-wordpress-client-uploads/infobae-wp/wp-content/uploads/2019/08/04082112/Guardiola-Klopp.jpg', description: 'El campeón y el subcampeón de la Premier League se enfrentan con el primer título de la temporada en juego. En la previa, hubo un duelo verbal entre Pep Guardiola y Jürgen Klopp. A las 11, por ESPN2', link: 'https://www.infobae.com/america/deportes/futbol-europeo/2019/08/04/manchester-city-vs-liverpool-community-shield-2019/' }, { title: 'Ireland\'s Hourihane bangs in two stunning free-kicks ahead of Villa\'s Premier League return - The42', date: '2019-08-04T11:33:00Z', image: 'https://img2.thejournal.ie/article/4752619/river/?height=400&version=4752623', description: null, link: 'https://www.the42.ie/conor-hourihane-free-kicks-leipzig-4752619-Aug2019/' }],
result = data.filter(o => Object.values(o).every(v => v !== null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use the filter function. The items variable contains your original data.
const filtered = items.filter(function(item) {
for (var key in item) {
if (null == item[key])
return false;
}
return true;
});

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! (:");
})

Not able to access object property with dashes

i'm confused about accessing a property from a javascript object.
In this scenario, i'm working with Node.js and Mongoose from find() method
My object:
{
_id: 52f541c7d2750f2d2cbf6d4a,
descriptions: {
'en-us': 'Lorem ipsum',
'pt-br': 'Os acessórios já não são mais meros coadjuvantes na harmonia de uma combinação, mas sim a sua assinatura de estilo, dando um caprichoso arremate ao que você escolheu ser pro dia de hoje.'
},
id: '1',
ids: { 'en-us': 'accessories', 'pt-br': 'acessorios' },
name: 'accessories',
names: { 'en-us': 'Accessories', 'pt-br': 'Acessórios' },
images: {
header: '/images/categories/86e3451ca755d31234e5fcad4af055f1',
unset: []
},
position: { x: 650, y: 735 },
active: true
}
Here's the thing:
I'm able to access any property except object.names, object.descriptions and object.ids, it returns 'undefined'.
But when i access the properties with Object.get('property'), i got the expected return.
Object.ids = undefined
Object['ids'] = undefined
Object.get('ids') = { 'en-us': 'accessories', 'pt-br': 'acessorios' }
Am i missing something here ? Maybe the issue occurs with special chars (In this case, dashes..?)
Hope you guys can help me. Best regards!

Categories

Resources