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

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

Related

Discord.js permissionOverwrites not working but no error at all

I've been working on a ticket bot for our company and ended up not being able to update a user's permissions per channel.
I cannot find any problems and the code is working apart of the permissions perfectly. I'm using DiscordJS 12.5.1.
Here's my code:
module.exports = {
name: 'ticket',
category: 'Ticket',
description: 'Creates a new ticket.',
aliases: ['new'],
usage: 'new',
userperms: [],
botperms: [],
run: async (client, message, args, prefix) => {
const discord = require('discord.js');
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
// parent: 'category id',
},
)
.then(async (channel) => {
let category = client.channels.cache.find(
(c) => c.name == '➣ Online Tickets' && c.type == 'category',
);
if (!category) throw new Error('Category channel does not exist');
channel.setParent(category.id);
// channel.permissionOverwrites.create(message.author.id, {VIEW_CHANNEL: true, SEND_MESSAGES: false});
// channel.permissionOverwrites.create(message.guild.roles.everyone, {VIEW_CHANNEL: false});
var embedParent = new discord.MessageEmbed()
.setTitle(`Beste, ${message.author.username}`)
.setDescription(
'Een van onze medewerkers helpt je z.s.m! Laat alvast een bericht achter zodat wij je zo goed mogelijk kunnen helpen. Om U zo goed mogelijk te kunnen helpen komen nu enkele vragen, gelieve deze te beantwoorden.\nReageer met 1️⃣ voor een technische vraag \nReageer met 2️⃣ voor boekhouding en juridische vragen.\nReageer met 3️⃣ voor een samenwerking.\nReageer met 4️⃣ voor overige vragen. \n\n ***LET OP: Als U errors krijgt op uw server, kunt U het beste een ticket aanmaken op de website: snip ***',
)
.setColor('007BFF')
.setFooter(
'© OnlineNode.nl 2021 - Ticket Systeem',
'https://media.discordapp.net/attachments/735827815521452133/830082858470604870/logo_400x400.png',
)
.setTimestamp();
channel.send(embedParent).then(function (embedParent) {
embedParent.react('1️⃣');
embedParent.react('2️⃣');
embedParent.react('3️⃣');
embedParent.react('4️⃣');
//embedParent.react("5️⃣")
});
message.guild.channels.cache
.find((c) => c.name == '🗃┃-discord-logs')
.send('New ticket has been submitted!');
});
},
};
Your permissionOverwrites array has an object where you repeat the allow key several times:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
As an object can't have two keys with the same name, it's basically the same as this:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
allow is an array of the permissions that are allowed for the user or role:
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
}
Another error is that when you set the parent of the channel with the setParent method, it overwrites the permissions you just added and sets them to the same as the parent channel.
The setParent method accepts an options object as its second parameter. One of its properties is lockPermissions. It tells whether to lock the permissions to what the parent's permissions are and its default value is true. To prevent synchronising permissions, you can set it to false instead, like this:
channel.setParent(category.id, { lockPermissions: false });
As Zsolt Meszaros mentioned, your permissions will need to be in an array.
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
// parent: 'category id',
},
)
Another thing, it is possible that your bot is setting the permissions, but then soon after inside your code, you changed the category the channel belongs in:
channel.setParent(category.id);
Also, I'm not sure, but there might be a chance that after you change the category, the permissions are being removed and then copied from what the category's permissions are, so you'll have to set the category before setting the permissions.

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

Mongoose save parent model with child model

How to save une ligne de stations? I have 2 shemas models station et. The method that I make doesn't work for me. see the pictures.
var LigneSchema = mongoose.Schema({
titre: String,
stations: [{ type: Schema.Types.ObjectId, ref: 'Station' }],
});
var StationSchema = mongoose.Schema({
titre: String,
lieu: String,
depart : boolean ,
arrive : boolean,
lignes: [{ type: Schema.Types.ObjectId, ref: 'Ligne' }]
});
var ligne = new Ligne({titre : req.body.titre, stations: []}) ;
ligne.save(function(err, data) {
console.log(data);
if(err) {
console.log(err);
res.status(500).send({message: "Une erreur s'est produite lors de la création du bus."});
} else {
res.send(data);
}
});
};

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