Delete an object from a nested Document in mongoose - javascript

I need to delete an object from an array of objects in mongoose.In the below example I need to delete a particular dish from an array of dishes.These array of dishes will be there inside array of categories
This dish object has to be deleted:
{
"dishName": "Dosa Cooks",
"dishType": "Veg",
"dishDescription": "A dosa is a thin batter-based dish originating from South India, made from a fermented batter predominantly consisting of lentils and rice.",
"dishPrice": "45",
"dishAvailability": true,
"dishImage": "Image",
"_id": "62f3ddf232bfba6253efbe85"
},
The main json present in mongo:
{
"_id": "62f3ddf232bfba6253efbe83",
"restaurantName": "Dhanush Cafe",
"restaurantId": "RESTN2500005",
"mobileNumber": "999809095",
"restaurantDishes": [
{
"category": "Tiffin",
"dishes": [
{
"dishName": "Dosa Cooks",
"dishType": "Veg",
"dishDescription": "A dosa is a thin batter-based dish originating from South India, made from a fermented batter predominantly consisting of lentils and rice.",
"dishPrice": "45",
"dishAvailability": true,
"dishImage": "Image",
"_id": "62f3ddf232bfba6253efbe85"
},
{
"dishName": "Idli",
"dishType": "Veg",
"dishDescription": "Idli or idly is a type of savoury rice cake, originating from the Indian subcontinent, popular as breakfast foods in Eastern and Southern India and in Sri Lanka.",
"dishPrice": "30",
"dishAvailability": true,
"dishImage": "Image",
"_id": "62f3ddf232bfba6253efbe86"
}
],
"_id": "62f3ddf232bfba6253efbe84"
},
{
"category": "Drinks",
"dishes": [
{
"dishName": "Tea",
"dishType": "Veg",
"dishDescription": "Tea is an aromatic beverage prepared by pouring hot or boiling water over cured or fresh leaves of Camellia sinensis",
"dishPrice": "25",
"dishAvailability": true,
"dishImage": "Image",
"_id": "62f3ddf232bfba6253efbe88"
},
{
"dishName": "Coffee",
"dishType": "Veg",
"dishDescription": "Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain flowering plants in the Coffea genus.",
"dishPrice": "30",
"dishAvailability": true,
"dishImage": "Image",
"_id": "62f3ddf232bfba6253efbe89"
}
],
"_id": "62f3ddf232bfba6253efbe87"
}
],
"createdAt": "2022-08-10T16:33:54.733Z",
"updatedAt": "2022-08-10T17:03:24.902Z",
"__v": 0
}

Related

Fetch and parse multiple arrays from .json file

I'm making a collection of all the movies I've watched and I keep all my data in movies.json. In movies.json there are multiple arrays, the first one being "MarvelMovies" with 2 movies in.
Next is "ComedyMovies" with also 4 movies.
I can console.log all the arrays, but I haven't figured out how to console.log each array (console.log the MarvelMovies array and ComedyMovies separately).
movies.json:
{
"MarvelMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
],
"ComedyMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
]
}
my js fetch code:
//DOM element
let movieSlider = document.querySelector(".mainSlider") //Grid til film
let movieTitle = document.querySelector(".mainSlider__title"); //genre titel
fetch('./media/json/movies.json')
.then(response => response.json())
.then((movies) => {
console.log(movies)
// console.log(response);
// });
// .then(movie => {
for (let i = 0; i < movies.length; i++) {
const element = movies[i];
movieSlider.innerHTML += `
<div class="mainSlider__item" style='background:url("${element.Poster}"); background-size:cover;'>
<div class="mainSlider__item-playButton">
<div class="mainSlider__item-title">${element.Title}</div>
<div class="mainSlider__item-info">${element.Year}</div>
<div class="mainSlider__item-desc">${element.Runtime}</div>
</div>
</div>
`
}
});
If you don't know the property names and also you don't need them. (They seem like categories). You can use Object.values and Array.flat methods to retrieve an array that contains just movies like below :
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);

nodejs axios JSON with Objects under the same name

So, My JS Looks Like This
#!/usr/bin/env node
var axios = require("axios");
var chalk = require("chalk");
var columnify = require('columnify')
var lineBreak = '-----------------------'
const info_url = `https://api.jikan.moe/v3/anime/22663`
axios.get(info_url, { headers: { Accept: "application/json" } }).then(anime => {
// console.log(anime.data.title)
var data = {
"Title (Romaji):": anime.data.title,
"Title (English):": anime.data.title_english,
"Title (Japanese):": anime.data.title_japanese,
"MAL ID": anime.data.mal_id,
"Title Synonyms:": anime.data.title_synonyms,
"Type": anime.data.type,
"Source:": anime.data.source,
"Status:": anime.data.status,
"Duration:": anime.data.duration,
"Rating:": anime.data.rating,
"Score:": anime.data.score,
"Rank": anime.data.rank,
"Popularity:": anime.data.popularity,
"Members:": anime.data.members,
"Favorites": anime.data.favorites,
"Premiered:": anime.data.premiered,
"Broadcast:": anime.data.broadcast,
"Genres:": anime.data.genres,
"\n": "\n",
}
console.log(columnify(data, {columns: [' ', ' ']}))
console.log(chalk.green("Synopsis:"))
console.log(anime.data.synopsis)
console.log(`\n`)
})
So Basically I'm Showing JSON Objects in the CLI, First Off here is the json file i'm currently using for this example
{
"request_hash": "request:anime:06c1f9aadcb4e3286fa86947ba8451bfc8c6d3a7",
"request_cached": true,
"request_cache_expiry": 73254,
"mal_id": 22663,
"url": "https://myanimelist.net/anime/22663/Seiken_Tsukai_no_World_Break",
"image_url": "https://cdn.myanimelist.net/images/anime/7/71769.jpg",
"trailer_url": "https://www.youtube.com/embed/zGXx54r4yWU?enablejsapi=1&wmode=opaque&autoplay=1",
"title": "Seiken Tsukai no World Break",
"title_english": "World Break: Aria of Curse for a Holy Swordsman",
"title_japanese": "聖剣使いの禁呪詠唱〈ワールドブレイク〉",
"title_synonyms": [
"Seiken Tsukai no Kinshuu Eishou",
"Warubure"
],
"type": "TV",
"source": "Light novel",
"episodes": 12,
"status": "Finished Airing",
"airing": false,
"aired": {
"from": "2015-01-12T00:00:00+00:00",
"to": "2015-03-30T00:00:00+00:00",
"prop": {
"from": {
"day": 12,
"month": 1,
"year": 2015
},
"to": {
"day": 30,
"month": 3,
"year": 2015
}
},
"string": "Jan 12, 2015 to Mar 30, 2015"
},
"duration": "24 min per ep",
"rating": "R - 17+ (violence & profanity)",
"score": 6.93,
"scored_by": 117100,
"rank": 3889,
"popularity": 602,
"members": 228214,
"favorites": 813,
"synopsis": "Seiken Tsukai no World Break takes place at Akane Private Academy where students who possess memories of their previous lives are being trained to use Ancestral Arts so that they can serve as defenders against monsters, called Metaphysicals, who randomly attack. Known as saviors, the students are broken up into two categories: the kurogane who are able to use their prana to summon offensive weapons and the kuroma who are able to use magic. The story begins six months prior to the major climax of the series during the opening ceremonies on the first day of the school year. After the ceremony is over, the main character, Moroha Haimura, meets a girl named Satsuki Ranjou who reveals that she was Moroha's little sister in a past life where Moroha was a heroic prince capable of slaying entire armies with his sword skills. Soon afterwards he meets another girl, Shizuno Urushibara, who eventually reveals that she also knew Moroha in an entirely different past life where he was a dark lord capable of using destructive magic but saved her from a life of slavery. Can those whose minds live in both the present and the past truly reach a bright future? Delve into the complex world of Seiken Tsukai no World Break to find out!",
"background": null,
"premiered": "Winter 2015",
"broadcast": "Mondays at 01:05 (JST)",
"related": {
"Adaptation": [
{
"mal_id": 57101,
"type": "manga",
"name": "Seiken Tsukai no World Break",
"url": "https://myanimelist.net/manga/57101/Seiken_Tsukai_no_World_Break"
}
]
},
"producers": [
{
"mal_id": 64,
"type": "anime",
"name": "Sotsu",
"url": "https://myanimelist.net/anime/producer/64/Sotsu"
}
],
"licensors": [
{
"mal_id": 102,
"type": "anime",
"name": "Funimation",
"url": "https://myanimelist.net/anime/producer/102/Funimation"
}
],
"studios": [
{
"mal_id": 51,
"type": "anime",
"name": "Diomedea",
"url": "https://myanimelist.net/anime/producer/51/Diomedea"
}
],
"genres": [
{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
"opening_themes": [
"\"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (eps 2-11)"
],
"ending_themes": [
"#1: \"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (ep 1)",
"#2: \"Magna Idea (マグナ・イデア)\" by fortuna (フォルトゥーナ) [Satsuki Ranjou (Ayana Taketatsu), Shizuno Urushibara (Aoi Yuuki), Haruka Momochi (Maaya Uchida), and Maya Shimon (Yui Ogura)] (eps 2-12)"
]
}
And The Part I'm Stuck On is the Genres Section because it has Multiple Genres with the Same Keys and I Don't Know how to Dynamically Display all of then in one Line of Text or one Sentence Rather
Here is the Genres Section of the JS:
"genres": [
{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
So Here is The Question, How Do I Display All The Genres Like This " Genres: Action, Fantasy, Harem, Romance, School, Supernatural "? and Have it Display like this if There are more genres than these?
If you want to get a string with the names of the genres, you could use .map() and .join(). Use .map() to turn the array into an array of genre names, from an array of objects. Then use .join() to combine the array into a string.
var data = {
"request_hash": "request:anime:06c1f9aadcb4e3286fa86947ba8451bfc8c6d3a7",
"request_cached": true,
"request_cache_expiry": 73254,
"mal_id": 22663,
"url": "https://myanimelist.net/anime/22663/Seiken_Tsukai_no_World_Break",
"image_url": "https://cdn.myanimelist.net/images/anime/7/71769.jpg",
"trailer_url": "https://www.youtube.com/embed/zGXx54r4yWU?enablejsapi=1&wmode=opaque&autoplay=1",
"title": "Seiken Tsukai no World Break",
"title_english": "World Break: Aria of Curse for a Holy Swordsman",
"title_japanese": "聖剣使いの禁呪詠唱〈ワールドブレイク〉",
"title_synonyms": [
"Seiken Tsukai no Kinshuu Eishou",
"Warubure"
],
"type": "TV",
"source": "Light novel",
"episodes": 12,
"status": "Finished Airing",
"airing": false,
"aired": {
"from": "2015-01-12T00:00:00+00:00",
"to": "2015-03-30T00:00:00+00:00",
"prop": {
"from": {
"day": 12,
"month": 1,
"year": 2015
},
"to": {
"day": 30,
"month": 3,
"year": 2015
}
},
"string": "Jan 12, 2015 to Mar 30, 2015"
},
"duration": "24 min per ep",
"rating": "R - 17+ (violence & profanity)",
"score": 6.93,
"scored_by": 117100,
"rank": 3889,
"popularity": 602,
"members": 228214,
"favorites": 813,
"synopsis": "Seiken Tsukai no World Break takes place at Akane Private Academy where students who possess memories of their previous lives are being trained to use Ancestral Arts so that they can serve as defenders against monsters, called Metaphysicals, who randomly attack. Known as saviors, the students are broken up into two categories: the kurogane who are able to use their prana to summon offensive weapons and the kuroma who are able to use magic. The story begins six months prior to the major climax of the series during the opening ceremonies on the first day of the school year. After the ceremony is over, the main character, Moroha Haimura, meets a girl named Satsuki Ranjou who reveals that she was Moroha's little sister in a past life where Moroha was a heroic prince capable of slaying entire armies with his sword skills. Soon afterwards he meets another girl, Shizuno Urushibara, who eventually reveals that she also knew Moroha in an entirely different past life where he was a dark lord capable of using destructive magic but saved her from a life of slavery. Can those whose minds live in both the present and the past truly reach a bright future? Delve into the complex world of Seiken Tsukai no World Break to find out!",
"background": null,
"premiered": "Winter 2015",
"broadcast": "Mondays at 01:05 (JST)",
"related": {
"Adaptation": [{
"mal_id": 57101,
"type": "manga",
"name": "Seiken Tsukai no World Break",
"url": "https://myanimelist.net/manga/57101/Seiken_Tsukai_no_World_Break"
}]
},
"producers": [{
"mal_id": 64,
"type": "anime",
"name": "Sotsu",
"url": "https://myanimelist.net/anime/producer/64/Sotsu"
}],
"licensors": [{
"mal_id": 102,
"type": "anime",
"name": "Funimation",
"url": "https://myanimelist.net/anime/producer/102/Funimation"
}],
"studios": [{
"mal_id": 51,
"type": "anime",
"name": "Diomedea",
"url": "https://myanimelist.net/anime/producer/51/Diomedea"
}],
"genres": [{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
"opening_themes": [
"\"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (eps 2-11)"
],
"ending_themes": [
"#1: \"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (ep 1)",
"#2: \"Magna Idea (マグナ・イデア)\" by fortuna (フォルトゥーナ) [Satsuki Ranjou (Ayana Taketatsu), Shizuno Urushibara (Aoi Yuuki), Haruka Momochi (Maaya Uchida), and Maya Shimon (Yui Ogura)] (eps 2-12)"
]
}
console.log(data.genres.map(e => e.name).join(", "))

access javascript value within the <script> tag with xpath

from this tag:
<script type = "text/javascript" > dataLayer.push({
"pageType": "productPage", "ecommerce": {
"currencyCode": "EUR",
"detail": {
"actionField": {"list": "Detail", "action": "detail"},
"products": [{
"name": "Desodorante Spray Alien",
"id": "10483558",
"price": "34,95",
"brand": "MUGLER",
"category": "higiene\/desodorantes",
"variant": "100 ML",
"dimension5": "Mucho stock",
"dimension6": "Unisex",
"dimension7": "CLARINS SPAIN, S.A",
"dimension8": "No",
"dimension9": "",
"metric2": 1
}]
},
"impressions": [{
"name": "Angel men recarga Eau de Toilette",
"id": "10059432",
"price": "47.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "100 ML ",
"list": "you may want",
"position": 1
}, {
"name": "Angel men rubber flask Eau de Toilette",
"id": "10351154",
"price": "42.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "50 ML ",
"list": "you may want",
"position": 2
}, {
"name": "Alien Shower Milk",
"id": "10483565",
"price": "26.00",
"brand": "MUGLER",
"category": "higiene_geles",
"variant": "200 ML ",
"list": "you may want",
"position": 3
}, {
"name": "Amen Desodorante en Stick",
"id": "10532706",
"price": "21.95",
"brand": "MUGLER",
"category": "hombre_desodorantes",
"variant": "75 ML ",
"list": "you may want",
"position": 4
}]
}
});
(window["rrApiOnReady"] = window["rrApiOnReady"] || []).push(function () {
retailrocket.productsGroup.post({
"groupId": 10483558,
"name": "Desodorante Spray Alien",
"price": 34.95,
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"isAvailable": true,
"categoryPaths": ["Higiene/Corporal", "Corporal", "Corporal/Higiene", "Higiene", "Higiene/Desodorante", "Marca/Mugler"],
"description": "El elixir de feminidad y de sensualidad del Eau de Parfum Alien en su versión desodorante en spray. Déjate envolver con los mismos acordes de la fragancia.",
"vendor": "MUGLER",
"products": {
"10483558": {
"isAvailable": true,
"name": "Desodorante Spray Alien",
"size": "100",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"price": 34.95,
"oldPrice": 34.95,
"params": {}
}
},
"params": {"medida": "ML", "subTitle": "Todo tipo de piel"},
"model": "Desodorante Spray Alien",
"typePrefix": "higiene_desodorantes",
"oldPrice": 34.95
});
rrApi.groupView([10483558]);
});
App.page.webshop = "DOU";
App.page.warehouse = ["ALM"];
App.page.codPostal = "";
</script>
I need to access some specific values of different functions (products, products.brand, impressions and impressions.id).
I tried to convert it to json dictionary, but it is a list and it gets converted into an array and I cannot access it with a "name" value.
How can I do this?
An example would be to select the script using some unique keyword which is only present in this script. Once you have that, you can use re_first to get the desired value. Take this as an example:
product_css = "script:contains('productPage')::text"
regex = 'name": "(.+?)"'
product_name = response.css(product_count_css).re_first(regex)
This will extract the first name. You can use re to tweak it further. Best of luck.

From an array of objects, extract only specific value of a property as array

I have JavaScript array of object with the following structure:
var arrayObj = [
{
"Rank": 1,
"Title": "The Shawshank Redemption",
"Description": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
"Runtime": 142,
"Genre": "Crime",
"Rating": 9.3,
"Metascore": 80,
"Votes": 1934970,
"Gross_Earning_in_Mil": 28.34,
"Director": "Frank Darabont",
"Actor": "Tim Robbins",
"Year": 1994
},
{
"Rank": 2,
"Title": "The Godfather",
"Description": "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
"Runtime": 175,
"Genre": "Crime",
"Rating": 9.2,
"Metascore": 100,
"Votes": 1323670,
"Gross_Earning_in_Mil": 134.97,
"Director": "Francis Ford Coppola",
"Actor": "Marlon Brando",
"Year": 1972
}]
I want to extract a field from each object except the "Director", and get an array containing the values, for example
[[1,
'The Shawshank Redemption',
'Two imprisoned men bond over a number of years, finding solace and
eventual redemption through acts of common decency.',
142,
'Crime',
9.3,
80,
1934970,
28.34,
'Tim Robbins',
1994 ],
[ 2,
'The Godfather',
'The aging patriarch of an organized crime dynasty transfers control
of his clandestine empire to his reluctant son.',
175,
'Crime',
9.2,
100,
1323670,
134.97,
'Marlon Brando',
1972 ]]
You could exclude a key by destructuring and using the rest properties.
var array = [{ Rank: 1, Title: "The Shawshank Redemption", Description: "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", Runtime: 142, Genre: "Crime", Rating: 9.3, Metascore: 80, Votes: 1934970, Gross_Earning_in_Mil: 28.34, Director: "Frank Darabont", Actor: "Tim Robbins", Year: 1994 }, { Rank: 2, Title: "The Godfather", Description: "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.", Runtime: 175, Genre: "Crime", Rating: 9.2, Metascore: 100, Votes: 1323670, Gross_Earning_in_Mil: 134.97, Director: "Francis Ford Coppola", Actor: "Marlon Brando", Year: 1972 }],
result = array.map(({ Director, ...o }) => o);
console.log(result);

ES6 Filter elements from an array within an array

I currently have 2 arrays. Each array has another array named "url".
{
"entities": [
{
"id": 0,
"companyName": "4-County Electric Power Assn",
"type": "E",
"state": "MS",
"code": "106641MS",
"url": [
{
"title": "4 County Electric",
"link": "http://www.4county.org/",
"href": "http://www.4county.org/"
}
]
},
{
"id": 1,
"companyName": "ACTON WATER DISTRICT OFFICE",
"type": "W",
"state": "MA",
"code": "W1771MA",
"url": [
{
"title": "Home — Acton Water District",
"link": "http://www.actonwater.com/",
"href": "http://www.actonwater.com/"
},
{
"title": "Contact Us — Acton Water District",
"link": "http://www.actonwater.com/customer-service/contact-us",
"href": "http://www.actonwater.com/customer-service/contact-us"
}
]
}
]
}
I'm trying to filter in each url array and remove any item that doesn't match the filter.
I've created a filter that successfully filters out the urls that dont contain the word "contact"
const regex = new RegExp('/contact\\b', 'g');
const companyColumn = db.get(`entities`).value()
const filteredData = companyColumn.map((a ,i) => {
return a.url.filter(({href}) => href.match(regex))
})
and get the response:
[ [],
[ { title: 'Contact Us — Acton Water District',
link: 'http://www.actonwater.com/customer-service/contact-us',
description: 'Office hours are Monday–Friday, 7:30 AM until 4:00 PM (excluding holidays) We \nare located at 693 Massachusetts Avenue, Acton, Ma 01720. Our mailing ...',
href: 'http://www.actonwater.com/customer-service/contact-us' } ] ]
boom. so it works.
But my question is how can I set the first item in the "entities" array to have an empty URL array, while the second "entities" item has only 1 item in it's URL array.
I feel so close...

Categories