Trouble figuring out how to delete hash from array based on conditions - arrays

I am trying to delete some number of hashes from an array if the particular keys in the hash contain or include some certain words. Find array below:
BANNED_WORDS = ['Hacked', 'hack', 'fraud', 'hacked']
data = [
{
"news_url": "https://www.benzinga.com/markets/cryptocurrency/21/10/23391043/north-vancouver-to-heat-buildings-with-bitcoin-mining",
"image_url": "https://crypto.snapi.dev/images/v1/m/v/fw-69939.jpeg",
"title": "North Vancouver To Heat Buildings With Bitcoin Mining",
"text": "Canadian hack Bitcoin (CRYPTO: BTC) mining firm MintGreen has partnered with state-owned Lonsdale Energy Corporation (LEC) to heat 100 residential and commercial buildings in North Vancouver with recovered energy from crypto mining.",
"source_name": "Benzinga",
"date": "Fri, 15 Oct 2021 12:16:19 -0400",
"topics": [
"mining"
],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"BTC"
]
},
{
"news_url": "https://u.today/ethereum-20-next-steps-to-mainnet-shared-by-ethereum-foundation",
"image_url": "https://crypto.snapi.dev/images/v1/b/t/10169-69937.jpg",
"title": "Ethereum 2.0 Next Steps to Mainnet Shared by Ethereum Foundation",
"text": "Ethereum (ETH) developers have entered final phase of testing before hotly anticipated ETH1-ETH2 transition",
"source_name": "UToday",
"date": "Fri, 15 Oct 2021 12:11:00 -0400",
"topics": [],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"ETH"
]
}
]
I am trying to delete any hash that either the text or title contains/include any word in the BANNED_WORDS array above.
I have tried the below and some other variations but none seem to be working. I am new to ruby, can someone please point me to what I am doing wrong, thanks.
data.select{|coin| coin[:text].split(" ").select{ |word| !BANNED_WORDS.include?(word) || coin[:title].split(" ").select{ |word| !BANNED_WORDS.include?(word)}}
So the result should be:
filtered_result = [
{
"news_url": "https://u.today/ethereum-20-next-steps-to-mainnet-shared-by-ethereum-foundation",
"image_url": "https://crypto.snapi.dev/images/v1/b/t/10169-69937.jpg",
"title": "Ethereum 2.0 Next Steps to Mainnet Shared by Ethereum Foundation",
"text": "Ethereum (ETH) developers have entered final phase of testing before hotly anticipated ETH1-ETH2 transition",
"source_name": "UToday",
"date": "Fri, 15 Oct 2021 12:11:00 -0400",
"topics": [],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"ETH"
]
}
]

This is a job for a regular expression.
R = /\b(?:#{BANNED_WORDS.join('|')})\b/
#=> /\b(?:Hacked|hack|fraud|hacked)\b/
data.reject { |h| h[:title].match?(R) || h[:text].match?(R) }
#=> [{:news_url=>"https://u.today/ethereum-20-next-steps...,
# ...
# :tickers=>["ETH"]}]
See Regexp#match?.
\b in the regular expression is a word boundary. They are there to prevent matches of, say, 'haskintosh' and 'defraud'.

Related

I am trying to create discord embeds, I do not know why this embed is working

Here is the code
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
await lib.discord.channels['#0.3.2'].messages.create({
"channel_id": ${context.params.event.channel_id},
"content": "",
"tts": false,
"embeds": [
{
"type": "rich",
"title": Staff Guidebook!,
"description": Here you can find the **punishment guide** and the **commands lists** to assist you!,
"color": 0xff0000,
"fields": [
{
"name": Dyno Commands List,
"value": https://dyno.gg/commands,
"inline": true
},
{
"name": Staff Punishment Guide,
"value": https://docs.google.com/spreadsheets/d/15JoaAvjOqaFDATEG91lS1UPOY-8gMIO112-kif2oiB8/edit?usp=sharing,
"inline": true
},
{
"name": Staffing Rules,
"value": - Staff cannot moderate other staff, you must create a support ticket instead.\n- You mut be as helpful as possible at all times.\n- You do not have to be proffesional at all times however when dealing with a staff \nsituation (aka. tickets) you must remain proffesional and use grammer at all times.\n- Being staff does not stop you from being within our rules. Any staff who break rules \nwill be punished accordingly by our support team.\n- You cannot leak any punishments or staff only information to other people, this can result in your removal from the staff team.\n- Keep calm when dealing with situations.\n- Always have evidence ready if you are going to punish someone.,
"inline": true
}
]
}
]
});
When I put it in, it comes out like a normal text message.

Can we change the sequence of json items?

Can we change the sequence of json items?
For example:
[
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In a complete graph G, which has 12 vertices, how many edges are there?",
"correct_answer": "66",
"incorrect_answers1": "67",
"incorrect_answers2 : "34",
"incorrect_answers3 : "11"
},
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In base 2, what is 1 + 1?",
"incorrect_answers1": "2",
"incorrect_answers2 : "01",
"correct_answer": "10",
"incorrect_answers3 : "11"
},
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In the hexadecimal system, what number comes after 9?",
"incorrect_answers1": "10",
"incorrect_answers2 : "The Number 0",
"correct_answer": "The Letter A",
"incorrect_answers3 : "16"
}
]
As mentioned in the comments that re-ordering JSON data is impossible and also not required.
For the current situation, you have to loop across the parent array containing the JSON objects, create a local array variable to get the list of re-ordered answers, push all the answers to this array and shuffle it using a library like lodash (https://lodash.com/docs/#shuffle) or a custom random functions, whatever works for your needs.
You can place this array within each object of this JSON while looping and give it a meaningful key like shuffled_answers.
So now your item structure will look like this:
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In base 2, what is 1 + 1?",
"incorrect_answers1": "2",
"incorrect_answers2" : "01",
"correct_answer": "10",
"incorrect_answers3" : "11",
"shuffled_answers": ["2", "11", "10", "11"]
}
You can then use this array to display answer choices in your UI to ask user the question and use the correct_answer key to compare the correct answer from the user's choice.
I'm linking here a video tutorial for a very similar App developed in Vue using the above logic. You can refer for more insight about apps like these and use it for your requirements.
Hope that helps.

Unable to access json data under square bracket - nodejs

I am using nodejs and below are the data returned from Google Book API. I wanted to access the information "Authors" from the data which is under a square bracket, however I am not able to access it. I tried a couple of methods but still fail to access them.
{
"kind": "books#volumes",
"totalItems": 42,
"items": [
{
"kind": "books#volume",
"id": "TpuJxgEACAAJ",
"etag": "kFhVXIpo2Aw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/TpuJxgEACAAJ",
"volumeInfo": {
"title": "The Guardians",
"authors": [
"John Grisham"
],
"publisher": "Random House Large Print",
"publishedDate": "2019-10-15",
"description": "The suspense never rests in John Grisham's pulse-pounding new legal thriller. The latest novel from the New York Times #1 bestselling author moves at breakneck speed, delivering some of his most inventive twists and turns yet. In the small north Florida town of Seabrook, a young lawyer named Keith Russo was shot dead at his desk as he worked late one night. The killer left no clues behind. There were no witnesses, no real suspects, no one with a motive. The police soon settled on Quincy Miller, a young black man who was once a client of Russo's. Quincy was framed, convicted, and sent to prison for life. For twenty-two years he languished in prison with no lawyer, no advocate on the outside. Then he wrote a letter to Guardian Ministries, a small innocence group founded by a lawyer/minister named Cullen Post. Guardian handles only a few innocence cases at a time, and Post is its only investigator. He travels the South fighting wrongful convictions and taking cases no one else will touch. With Quincy Miller, though, he gets far more than he bargained for. Powerful, ruthless people murdered Keith Russo, and they do not want Quincy exonerated. They killed one lawyer twenty-two years ago, and they will kill another one without a second thought.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0525639381"
},
{
"type": "ISBN_13",
"identifier": "9780525639381"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 480,
"printType": "BOOK",
"categories": [
"Fiction"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"panelizationSummary": {
"containsEpubBubbles": false,
"containsImageBubbles": false
},
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=TpuJxgEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=TpuJxgEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.com.my/books?id=TpuJxgEACAAJ&dq=the+guardian+inauthor:john+grisham&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.com.my/books?id=TpuJxgEACAAJ&dq=the+guardian+inauthor:john+grisham&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/The_Guardians.html?hl=&id=TpuJxgEACAAJ"
},
"saleInfo": {
"country": "MY",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "MY",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://play.google.com/books/reader?id=TpuJxgEACAAJ&hl=&printsec=frontcover&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "In the small north Florida town of Seabrook, a young lawyer named Keith Russo was shot dead at his desk as he worked late one night."
}
}
]
}
Below is how I try to access:
const volumeInfo.authors = body.items[0].volumeInfo.authors;
The nodejs will crash under body.items[0] when I run it. I also try to get the keys underneath "items" but it will flag errors.
Have you tried parsing the response into JSON using JSON.parse method?

How to convert Google Sheets v4 api output to a normal JavaScript Array of Objects?

I tried to find answers for this but everything seems to pertain to other things or the previous versions of the api.
I'm trying to use a google spreadsheet as a basic json backend. My spreadsheets looks something like this:
Google sheets api v4 has a method called batchGet. The call (https://sheets.googleapis.com/v4/spreadsheets/1kEhCvvbHt-9BZgKKp-eQsy7l0AkFtZ9_7cIhvyVGLZ8/values:batchGet?ranges=data&majorDimension=ROWS) outputs my spreadsheet to be something like this:
{
"spreadsheetId": "1kEhCvvbHt-9BZgKKp-eQsy7l0AkFtZ9_7cIhvyVGLZ8",
"valueRanges": [
{
"range": "data!A1:O1000",
"majorDimension": "ROWS",
"values": [
[
"id",
"name",
"location",
"Description",
"website",
"image",
"Address",
"lat",
"lng",
"color",
"Products",
"Cartridges",
"High-CBD Tincture",
"THCa Crystalline"
],
[
"1",
"Erba",
"West Los Angeles",
"Erba’s philosophy is to carry only the most top-tier products, and never sacrifice quality by all means necessary. You’ll feel the difference once you step foot inside their impressive shop.",
"http://erbacollective.com/",
"https://static.wixstatic.com/media/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png",
"12320 W Pico Blvd, Los Angeles, CA 90064\n",
"34.028126",
"-118.452295",
"#7CB711",
"Full-spectrum vape carts, THCa crystalline and tincture.",
"TRUE",
"FALSE",
"TRUE"
],
[
"2",
"99 High Tide",
"Malibu",
"99 High Tide is Malibu's only medical marijuana dispensary. They are a visionary collective of Cannabis experts, artists, DJs, growers, healers & shamans.",
"http://99hightide.com/",
"https://static.wixstatic.com/media/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png",
"22775 Pacific Coast Hwy, Malibu, CA 90265\n",
"34.039466",
"-118.671939",
"#3A8ABD",
"Full-spectrum vape carts and THCa crystalline.",
"TRUE",
"FALSE",
"TRUE"
],
[
What I need is something like this (in order for it to play nicely in React):
"rows": [
{
"id": 1,
"name": "Erba",
"location": "West Los Angeles",
"description": "Erba’s philosophy is to carry only the most top-tier products, and never sacrifice quality by all means necessary. You’ll feel the difference once you step foot inside their impressive shop.",
"website": "http://erbacollective.com/",
"image": "https://static.wixstatic.com/media/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png",
"address": "12320 W Pico Blvd, Los Angeles, CA 90064\n",
"lat": 34.028126,
"lng": -118.452295,
"color": "#7CB711",
"products": "Full-spectrum vape carts, THCa crystalline and tincture.",
"cartridges": "TRUE",
"high-cbdtincture": "FALSE",
"thcacrystalline": "TRUE"
},
{
"id": 2,
"name": "99 High Tide",
"location": "Malibu",
"description": "99 High Tide is Malibu's only medical marijuana dispensary. They are a visionary collective of Cannabis experts, artists, DJs, growers, healers & shamans.",
"website": "http://99hightide.com/",
"image": "https://static.wixstatic.com/media/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png",
"address": "22775 Pacific Coast Hwy, Malibu, CA 90265\n",
"lat": 34.039466,
"lng": -118.671939,
"color": "#3A8ABD",
"products": "Full-spectrum vape carts and THCa crystalline.",
"cartridges": "TRUE",
"high-cbdtincture": "FALSE",
"thcacrystalline": "TRUE"
},
{
"id": 3,
"name": "The Higher Path",
"location": "Sherman Oaks",
"description": "Named the Best Dispensary in Los Angeles 2016, The Higher Path Collective serves both medical patients and adult use recreational consumers! Hailing from Northern California, The Higher Path’s owner Jerred Kiloh brings a very different mentality of medicine with him to Southern California—one that puts the patient before everything else. Since opening in 2013, it’s been The Higher Path’s focus and passion to help provide patients with the knowledge and medicine they need.",
"website": "https://www.thehigherpath.com/",
"image": "https://static.wixstatic.com/media/e4d816_8304a48460884d9ea5cac420164fe9cb~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_8304a48460884d9ea5cac420164fe9cb~mv2.png",
"address": "14080 Ventura Blvd, Sherman Oaks, CA 91423\n",
"lat": 34.149202,
"lng": -118.439813,
"color": "#9050A4",
"products": "Full-spectrum vape carts.",
"cartridges": "TRUE",
"high-cbdtincture": "FALSE",
"thcacrystalline": "FALSE"
},
{
"id": 4,
"name": "Sespe Creek",
"location": "Ojai",
"description": "Sespe aims to bring the best of our local region’s strains, concentrates, drinks, edibles and topicals to patients with all budgets, health backgrounds and tastes.",
"website": "http://sespe.org/",
"image": "https://static.wixstatic.com/media/e4d816_5fe69dd77579484a8980aeffc8beacb3~mv2.png/v1/fill/w_173,h_173,al_c,usm_0.66_1.00_0.01/e4d816_5fe69dd77579484a8980aeffc8beacb3~mv2.png",
"address": "408 Bryant Cir Unit C, Ojai, CA 93023\n",
"lat": 34.443072,
"lng": -119.237926,
"color": "#DC3267",
"products": "Entire lineup of full-spectrum extracts.",
"cartridges": "FALSE",
"high-cbdtincture": "FALSE",
"thcacrystalline": "FALSE"
},
How do I convert the output data into a nice json array of objects?
You need to loop through the output and create your own Object.
function makeObject() {
var batchResponse; // This is the response from batchGet()
batchResponse = "{\"spreadsheetId\": \"1kEhCvvbHt-9BZgKKp-eQsy7l0AkFtZ9_7cIhvyVGLZ8\",\"valueRanges\": [{\"range\": \"data!A1:O1000\",\"majorDimension\": \"ROWS\",\"values\": [[\"id\",\"name\",\"location\",\"Description\",\"website\",\"image\",\"Address\",\"lat\",\"lng\",\"color\",\"Products\",\"Cartridges\",\"High-CBD Tincture\",\"THCa Crystalline\"],[\"1\",\"Erba\",\"West Los Angeles\",\"Erba’s philosophy is to carry only the most top-tier products, and never sacrifice quality by all means necessary. You’ll feel the difference once you step foot inside their impressive shop.\",\"http:\/\/erbacollective.com\/\",\"https:\/\/static.wixstatic.com\/media\/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png\/v1\/fill\/w_173,h_173,al_c,usm_0.66_1.00_0.01\/e4d816_49fd88e6e519486b8be81fd955a52b35~mv2.png\",\"12320 W Pico Blvd, Los Angeles, CA 90064\\n\",\"34.028126\",\"-118.452295\",\"#7CB711\",\"Full-spectrum vape carts, THCa crystalline and tincture.\",\"TRUE\",\"FALSE\",\"TRUE\"],[\"2\",\"99 High Tide\",\"Malibu\",\"99 High Tide is Malibu's only medical marijuana dispensary. They are a visionary collective of Cannabis experts, artists, DJs, growers, healers & shamans.\",\"http:\/\/99hightide.com\/\",\"https:\/\/static.wixstatic.com\/media\/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png\/v1\/fill\/w_173,h_173,al_c,usm_0.66_1.00_0.01\/e4d816_a576375fe1104c1399cc0249b7c3818e~mv2.png\",\"22775 Pacific Coast Hwy, Malibu, CA 90265\\n\",\"34.039466\",\"-118.671939\",\"#3A8ABD\",\"Full-spectrum vape carts and THCa crystalline.\",\"TRUE\",\"FALSE\",\"TRUE\"]]}]\n}";
batchResponse = JSON.parse(batchResponse); // Convert from JSON to Object
var batchRowValues = batchResponse["valueRanges"][0]["values"];
var rows = [];
for (var i=1; i<batchRowValues.length; i++) {
var rowObject = {};
for (var j=0; j<batchRowValues[i].length; j++) {
rowObject[batchRowValues[0][j]] = batchRowValues[i][j];
}
rows.push(rowObject);
}
return rows;
}
Note:
I hard-coded the example JSON output from batchGet() you provided
This function returns an Array. If you want it to return JSON, then the final line should read return JSON.stringify(rows);.

How to convert JSON Http response to Array in AngularJS 2

I'm doing a Http get in Angular 2 and the response is a JSON. However, i'm trying to use this in a ngFor but i can't because it isn't an Array.
How can I convert JSON to Array in Angular 2? I searched in many websites but didn't discover a effective way to do that.
Edit 1:
The response is like that:
{
"adult": false,
"backdrop_path": "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_language": "en",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": 0.5,
"poster_path": null,
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-12",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"video": false,
"vote_average": 7.8,
"vote_count": 3439
}
I think if you want to pass from json to array you could do the following command:
var arr = []
for(i in json_object){
arr.push(i)
arr.push(json_object[i])
}
Then you have every keys in the even index and every contents in the odd index
Well, I really don't see the point here. Arrays are for operating with lists of similar objects or types, not for complex structures. If you had a bunch of objects similar to the one you show, then it would make sense. Anyways, if you really want an array then you could do it with recursion and create a flat array of the properties.
var flatPropertyArray = [];
function flatten(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object")
flatten(obj[property]);
else
flatPropertyArray.push(property);
}
}
}
pass your JSON into the flatten func.

Resources