I have a list of movies and would like to sort them by genre: I got pretty close with my solution but there is one problem: each movie has an ARRAY of genres, not one singular genre.
{
"movies": [
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/d6822b7b-48bb-4b78-ad5e-9ba04c517ec8.jpg",
"cast": [
"Christian Bale",
"Heath Ledger",
"Aaron Eckhart"
],
"classification": "13+",
"director": "Christopher Nolan",
"genres": [
"Action",
"Crime",
"Drama"
],
"id": "d6822b7b-48bb-4b78-ad5e-9ba04c517ec8",
"imdb_rating": 9.0,
"length": "2h 32min",
"overview": "Batman raises the stakes in his war on crime. With the help of Lt. Jim Gordon and District Attorney Harvey Dent, Batman sets out to dismantle the remaining criminal organizations that plague the streets. The partnership proves to be effective, but they soon find themselves prey to a reign of chaos unleashed by a rising criminal mastermind known to the terrified citizens of Gotham as the Joker.",
"poster": "https://wookie.codesubmit.io/static/posters/d6822b7b-48bb-4b78-ad5e-9ba04c517ec8.jpg",
"released_on": "2008-07-16T00:00:00",
"slug": "the-dark-knight-2008",
"title": "The Dark Knight"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/a9d94d6e-4cab-44a9-8eec-d44ad6332b6d.jpg",
"cast": [
"John Travolta",
"Uma Thurman",
"Samuel L. Jackson"
],
"classification": "18+",
"director": "Quentin Tarantino",
"genres": [
"Crime",
"Drama"
],
"id": "a9d94d6e-4cab-44a9-8eec-d44ad6332b6d",
"imdb_rating": 8.9,
"length": "2h 34min",
"overview": "A burger-loving hit man, his philosophical partner, a drug-addled gangster's moll and a washed-up boxer converge in this sprawling, comedic crime caper. Their adventures unfurl in three stories that ingeniously trip back and forth in time.",
"poster": "https://wookie.codesubmit.io/static/posters/a9d94d6e-4cab-44a9-8eec-d44ad6332b6d.jpg",
"released_on": "1994-09-10T00:00:00",
"slug": "pulp-fiction-1994",
"title": "Pulp Fiction"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/4ec83f0e-eede-4453-8f87-461525e21f6e.jpg",
"cast": [
"Liam Neeson",
"Ralph Fiennes",
"Ben Kingsley"
],
"classification": "18+",
"director": "Steven Spielberg",
"genres": [
"Biography",
"Drama",
"History"
],
"id": "4ec83f0e-eede-4453-8f87-461525e21f6e",
"imdb_rating": 8.9,
"length": "3h 15min",
"overview": "The true story of how businessman Oskar Schindler saved over a thousand Jewish lives from the Nazis while they worked as slaves in his factory during World War II.",
"poster": "https://wookie.codesubmit.io/static/posters/4ec83f0e-eede-4453-8f87-461525e21f6e.jpg",
"released_on": "1993-12-15T00:00:00",
"slug": "schindlers-list-1993",
"title": "Schindler's List"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/f3d91837-a2ff-4250-99b0-e8c9c036a23a.jpg",
"cast": [
"Shameik Moore",
"Jake Johnson",
"Hailee Steinfeld"
],
"classification": "7+",
"director": [
"Bob Persichetti",
"Peter Ramsey",
"Rodney Rothman"
],
"genres": [
"Animation",
"Action",
"Adventure"
],
"id": "f3d91837-a2ff-4250-99b0-e8c9c036a23a",
"imdb_rating": 8.5,
"length": "1h 57min",
"overview": "Miles Morales is juggling his life between being a high school student and being a spider-man. When Wilson \"Kingpin\" Fisk uses a super collider, others from across the Spider-Verse are transported to this dimension.",
"poster": "https://wookie.codesubmit.io/static/posters/f3d91837-a2ff-4250-99b0-e8c9c036a23a.jpg",
"released_on": "2018-12-06T00:00:00",
"slug": "spider-man-into-the-spider-verse-2018",
"title": "Spider-Man: Into the Spider-Verse"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/9a70e529-9070-4a2f-963c-c5bb253cc721.jpg",
"cast": [
"Robert Downey Jr.",
"Chris Hemsworth",
"Mark Ruffalo"
],
"classification": "13+",
"director": [
"Anthony Russo",
"Joe Russo"
],
"genres": [
"Action",
"Adventure",
"Sci-Fi"
],
"id": "9a70e529-9070-4a2f-963c-c5bb253cc721",
"imdb_rating": 8.5,
"length": "2h 29min",
"overview": "As the Avengers and their allies have continued to protect the world from threats too large for any one hero to handle, a new danger has emerged from the cosmic shadows: Thanos. A despot of intergalactic infamy, his goal is to collect all six Infinity Stones, artifacts of unimaginable power, and use them to inflict his twisted will on all of reality. Everything the Avengers have fought for has led up to this moment - the fate of Earth and existence itself has never been more uncertain.",
"poster": "https://wookie.codesubmit.io/static/posters/9a70e529-9070-4a2f-963c-c5bb253cc721.jpg",
"released_on": "2018-04-25T00:00:00",
"slug": "avengers-infinity-war-2018",
"title": "Avengers: Infinity War"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/4d949e14-b08b-47fb-bab0-22c732dbedf3.jpg",
"cast": [
"Harrison Ford",
"Karen Allen",
"Paul Freeman"
],
"classification": "7+",
"director": "Steven Spielberg",
"genres": [
"Action",
"Adventure"
],
"id": "4d949e14-b08b-47fb-bab0-22c732dbedf3",
"imdb_rating": 8.5,
"length": "1h 55min",
"overview": "When Dr. Indiana Jones – the tweed-suited professor who just happens to be a celebrated archaeologist – is hired by the government to locate the legendary Ark of the Covenant, he finds himself up against the entire Nazi regime.",
"poster": "https://wookie.codesubmit.io/static/posters/4d949e14-b08b-47fb-bab0-22c732dbedf3.jpg",
"released_on": "1981-06-12T00:00:00",
"slug": "raiders-of-the-lost-ark-1981",
"title": "Raiders of the Lost Ark"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/8de5e9be-ec40-4687-9b01-be1af3ace1d7.jpg",
"cast": [
"Christian Bale",
"Michael Caine",
"Ken Watanabe"
],
"classification": "13+",
"director": "Christopher Nolan",
"genres": [
"Action",
"Adventure"
],
"id": "8de5e9be-ec40-4687-9b01-be1af3ace1d7",
"imdb_rating": 8.2,
"length": "2h 20min",
"overview": "Driven by tragedy, billionaire Bruce Wayne dedicates his life to uncovering and defeating the corruption that plagues his home, Gotham City. Unable to work within the system, he instead creates a new identity, a symbol of fear for the criminal underworld - The Batman.",
"poster": "https://wookie.codesubmit.io/static/posters/8de5e9be-ec40-4687-9b01-be1af3ace1d7.jpg",
"released_on": "2005-06-10T00:00:00",
"slug": "batman-begins-2005",
"title": "Batman Begins"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/554347b2-a340-4e35-b385-07e067ef302a.jpg",
"cast": [
"Robin Williams",
"Matt Damon",
"Ben Affleck"
],
"classification": "18+",
"director": "Gus Van Sant",
"genres": [
"Drama",
"Romance"
],
"id": "554347b2-a340-4e35-b385-07e067ef302a",
"imdb_rating": 8.3,
"length": "2h 6min",
"overview": "Will Hunting has a genius-level IQ but chooses to work as a janitor at MIT. When he solves a difficult graduate-level math problem, his talents are discovered by Professor Gerald Lambeau, who decides to help the misguided youth reach his potential. When Will is arrested for attacking a police officer, Professor Lambeau makes a deal to get leniency for him if he will get treatment from therapist Sean Maguire.",
"poster": "https://wookie.codesubmit.io/static/posters/554347b2-a340-4e35-b385-07e067ef302a.jpg",
"released_on": "1997-12-05T00:00:00",
"slug": "good-will-hunting-1997",
"title": "Good Will Hunting"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/84b17b50-5c6b-4c00-a798-f83ddda0187d.jpg",
"cast": [
"Anthony Gonzalez",
"Gael Garcia Bernal",
"Benjamin Bratt"
],
"classification": "7+",
"director": [
"Lee Unkrich",
"Adrian Molina"
],
"genres": [
"Animation",
"Adventure",
"Family"
],
"id": "84b17b50-5c6b-4c00-a798-f83ddda0187d",
"imdb_rating": 8.4,
"length": "1h 45min",
"overview": "Despite his family’s baffling generations-old ban on music, Miguel dreams of becoming an accomplished musician like his idol, Ernesto de la Cruz. Desperate to prove his talent, Miguel finds himself in the stunning and colorful Land of the Dead following a mysterious chain of events. Along the way, he meets charming trickster Hector, and together, they set off on an extraordinary journey to unlock the real story behind Miguel's family history.",
"poster": "https://wookie.codesubmit.io/static/posters/84b17b50-5c6b-4c00-a798-f83ddda0187d.jpg",
"released_on": "2017-10-27T00:00:00",
"slug": "coco-2017",
"title": "Coco"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/372702a0-3e49-4bf3-812a-0c241a8c5ac9.jpg",
"cast": [
"Robert De Niro",
"Jodie Foster",
"Cybill Shepherd"
],
"classification": "18+",
"director": "Martin Scorsese",
"genres": [
"Crime",
"Drama"
],
"id": "372702a0-3e49-4bf3-812a-0c241a8c5ac9",
"imdb_rating": 8.3,
"length": "1h 54min",
"overview": "A mentally unstable Vietnam War veteran works as a night-time taxi driver in New York City where the perceived decadence and sleaze feeds his urge for violent action, attempting to save a preadolescent prostitute in the process.",
"poster": "https://wookie.codesubmit.io/static/posters/372702a0-3e49-4bf3-812a-0c241a8c5ac9.jpg",
"released_on": "1976-02-07T00:00:00",
"slug": "taxi-driver-1976",
"title": "Taxi Driver"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/b7e23588-8d87-402f-8f13-87cbf8e51812.jpg",
"cast": [
"Benedict Cumberbatch",
"Keira Knightley",
"Matthew Goode"
],
"classification": "13+",
"director": "Morten Tyldum",
"genres": [
"Biography",
"Drama",
"Thriller"
],
"id": "b7e23588-8d87-402f-8f13-87cbf8e51812",
"imdb_rating": 8.0,
"length": "1h 54min",
"overview": "Based on the real life story of legendary cryptanalyst Alan Turing, the film portrays the nail-biting race against time by Turing and his brilliant team of code-breakers at Britain's top-secret Government Code and Cypher School at Bletchley Park, during the darkest days of World War II.",
"poster": "https://wookie.codesubmit.io/static/posters/b7e23588-8d87-402f-8f13-87cbf8e51812.jpg",
"released_on": "2014-11-14T00:00:00",
"slug": "the-imitation-game-2014",
"title": "The Imitation Game"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/95f34949-33c4-4cab-ac58-597f0db1dd57.jpg",
"cast": [
"Ulrich Muehe",
"Martina Gedeck",
"Sebastian Koch"
],
"classification": "18+",
"director": "Florian Henckel von Donnersmarck",
"genres": [
"Drama",
"Thriller"
],
"id": "95f34949-33c4-4cab-ac58-597f0db1dd57",
"imdb_rating": 8.4,
"length": "2h 17min",
"overview": "A tragic love story set in East Berlin with the backdrop of an undercover Stasi controlled culture. Stasi captain Wieler is ordered to follow author Dreyman and plunges deeper and deeper into his life until he reaches the threshold of doubting the system.",
"poster": "https://wookie.codesubmit.io/static/posters/95f34949-33c4-4cab-ac58-597f0db1dd57.jpg",
"released_on": "2006-03-15T00:00:00",
"slug": "the-lives-of-others-2006",
"title": "The Lives of Others"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/0bf56a90-5f7b-4108-9d0b-01ad77f0a310.jpg",
"cast": [
"Malcolm McDowell",
"Patick Magee",
"Michael Bates"
],
"classification": "18+",
"director": "Stanley Kubrick",
"genres": [
"Crime",
"Drama",
"Sci-Fi"
],
"id": "0bf56a90-5f7b-4108-9d0b-01ad77f0a310",
"imdb_rating": 8.3,
"length": "2h 16min",
"overview": "Demonic gang-leader Alex goes on the spree of rape, mugging and murder with his pack of \"droogs\". But he's a boy who also likes Beethoven's Ninth and a bit of \"the old in-out, in-out\". He later finds himself at the mercy of the state and its brainwashing experiment designed to take violence off the streets.",
"poster": "https://wookie.codesubmit.io/static/posters/0bf56a90-5f7b-4108-9d0b-01ad77f0a310.jpg",
"released_on": "1971-12-18T00:00:00",
"slug": "a-clockwork-orange-1971",
"title": "A Clockwork Orange"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/566ade1b-7fb8-41eb-8b51-f010c3a246ac.jpg",
"cast": [
"Brad Pitt",
"Diane Kruger",
"Eli Roth"
],
"classification": "18+",
"director": "Quentin Tarantino",
"genres": [
"Adventure",
"Drama",
"War"
],
"id": "566ade1b-7fb8-41eb-8b51-f010c3a246ac",
"imdb_rating": 8.3,
"length": "2h 33min",
"overview": "In Nazi-occupied France during World War II, a group of Jewish-American soldiers known as \"The Basterds\" are chosen specifically to spread fear throughout the Third Reich by scalping and brutally killing Nazis. The Basterds, lead by Lt. Aldo Raine soon cross paths with a French-Jewish teenage girl who runs a movie theater in Paris which is targeted by the soldiers.",
"poster": "https://wookie.codesubmit.io/static/posters/566ade1b-7fb8-41eb-8b51-f010c3a246ac.jpg",
"released_on": "2009-08-18T00:00:00",
"slug": "inglourious-basterds-2009",
"title": "Inglourious Basterds"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/d8cbdc3d-c683-4a59-aae3-9a7327f0743a.jpg",
"cast": [
"Tommy Lee Jones",
"Javier Bardem",
"Josh Brolin"
],
"classification": "18+",
"director": [
"Ethan Coen",
"Joel Coen"
],
"genres": [
"Crime",
"Drama",
"Thriller"
],
"id": "d8cbdc3d-c683-4a59-aae3-9a7327f0743a",
"imdb_rating": 8.1,
"length": "2h 2min",
"overview": "Llewelyn Moss stumbles upon dead bodies, $2 million and a hoard of heroin in a Texas desert, but methodical killer Anton Chigurh comes looking for it, with local sheriff Ed Tom Bell hot on his trail. The roles of prey and predator blur as the violent pursuit of money and justice collide.",
"poster": "https://wookie.codesubmit.io/static/posters/d8cbdc3d-c683-4a59-aae3-9a7327f0743a.jpg",
"released_on": "2007-11-08T00:00:00",
"slug": "no-country-for-old-men-2007",
"title": "No Country for Old Men"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/9fb4b518-b407-467d-b076-fb2d2c541593.jpg",
"cast": [
"Brie Larson",
"Jacob Tremblay",
"Sean Bridgers"
],
"classification": "18+",
"director": "Lenny Abrahamson",
"genres": [
"Drama",
"Thriller"
],
"id": "9fb4b518-b407-467d-b076-fb2d2c541593",
"imdb_rating": 8.2,
"length": "1h 58min",
"overview": "Jack is a young boy of 5 years old who has lived all his life in one room. He believes everything within it are the only real things in the world. But what will happen when his Ma suddenly tells him that there are other things outside of Room?",
"poster": "https://wookie.codesubmit.io/static/posters/9fb4b518-b407-467d-b076-fb2d2c541593.jpg",
"released_on": "2015-10-16T00:00:00",
"slug": "room-2015",
"title": "Room"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/2dfccc2c-42cc-4a06-81a7-8d1da3284283.jpg",
"cast": [
"Harrison Ford",
"Sean Connery",
"Alison Doody"
],
"classification": "13+",
"director": "Steven Spielberg",
"genres": [
"Action",
"Adventure"
],
"id": "2dfccc2c-42cc-4a06-81a7-8d1da3284283",
"imdb_rating": 8.2,
"length": "2h 7min",
"overview": "When Dr. Henry Jones Sr. suddenly goes missing while pursuing the Holy Grail, eminent archaeologist Indiana must team up with Marcus Brody, Sallah and Elsa Schneider to follow in his father's footsteps and stop the Nazis from recovering the power of eternal life.",
"poster": "https://wookie.codesubmit.io/static/posters/2dfccc2c-42cc-4a06-81a7-8d1da3284283.jpg",
"released_on": "1989-05-24T00:00:00",
"slug": "indiana-jones-and-the-last-crusade-1989",
"title": "Indiana Jones and the Last Crusade"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/be4b37a6-a8c3-476c-996f-3b9d2aaabfd5.jpg",
"cast": [
"Al Pacino",
"Michelle Pfeiffer",
"Steven Bauer"
],
"classification": "18+",
"director": "Brian De Palma",
"genres": [
"Crime",
"Drama"
],
"id": "be4b37a6-a8c3-476c-996f-3b9d2aaabfd5",
"imdb_rating": 8.3,
"length": "2h 50min",
"overview": "After getting a green card in exchange for assassinating a Cuban government official, Tony Montana stakes a claim on the drug trade in Miami. Viciously murdering anyone who stands in his way, Tony eventually becomes the biggest drug lord in the state, controlling nearly all the cocaine that comes through Miami. But increased pressure from the police, wars with Colombian drug cartels and his own drug-fueled paranoia serve to fuel the flames of his eventual downfall.",
"poster": "https://wookie.codesubmit.io/static/posters/be4b37a6-a8c3-476c-996f-3b9d2aaabfd5.jpg",
"released_on": "1983-12-08T00:00:00",
"slug": "scarface-1983",
"title": "Scarface"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/57a1aec1-e950-46b0-bbb2-2897b8c5233e.jpg",
"cast": [
"Bruce Willis",
"Haley Joel Osment",
"Toni Collette"
],
"classification": "13+",
"director": "M. Night Shyamalan",
"genres": [
"Drama",
"Mystery",
"Thriller"
],
"id": "57a1aec1-e950-46b0-bbb2-2897b8c5233e",
"imdb_rating": 8.1,
"length": "1h 47min",
"overview": "A psychological thriller about an eight year old boy named Cole Sear who believes he can see into the world of the dead. A child psychologist named Malcolm Crowe comes to Cole to help him deal with his problem, learning that he really can see ghosts of dead people.",
"poster": "https://wookie.codesubmit.io/static/posters/57a1aec1-e950-46b0-bbb2-2897b8c5233e.jpg",
"released_on": "1999-08-06T00:00:00",
"slug": "the-sixth-sense-1999",
"title": "The Sixth Sense"
},
{
"backdrop": "https://wookie.codesubmit.io/static/backdrops/529c7379-ccfe-4003-a2ba-6c0a2ffd6704.jpg",
"cast": [
"Colin Firth",
"Geoffrey Rush",
"Helena Bonham Carter"
],
"classification": "18+",
"director": "Tom Hooper",
"genres": [
"Biography",
"Drama",
"History"
],
"id": "529c7379-ccfe-4003-a2ba-6c0a2ffd6704",
"imdb_rating": 8.0,
"length": "1h 58min",
"overview": "The King's Speech tells the story of the man who became King George VI, the father of Queen Elizabeth II. After his brother abdicates, George ('Bertie') reluctantly assumes the throne. Plagued by a dreaded stutter and considered unfit to be king, Bertie engages the help of an unorthodox speech therapist named Lionel Logue. Through a set of unexpected techniques, and as a result of an unlikely friendship, Bertie is able to find his voice and boldly lead the country into war.",
"poster": "https://wookie.codesubmit.io/static/posters/529c7379-ccfe-4003-a2ba-6c0a2ffd6704.jpg",
"released_on": "2010-09-06T00:00:00",
"slug": "the-kings-speech-2010",
"title": "The King's Speech"
}
]
}
Storing the movies in a variable: I attempted to sort them like this:
let out_data = {}
movies.forEach(function(row: { genres: string | number }) {
if (out_data[row.genres.flatMap(m => m)]) {
out_data[row.genres.flatMap(m => m)].push(row)
} else {
out_data[row.genres.flatMap(m => m)] = [row]
}
})
console.log(out_data)
However, the result I got looked like this:
The List was sorted, however not into each individual genre, but rather by a list of genres.
Is there any way to sort them by each INDIVIDUAL genre: i.e.
Action: movie A, movie B, movie C
Thriller: movie A, movie B
etc. etc.
row.genres.flatMap(m => m) does nothing. This will return an exact copy of row.genres. So when you do out_data[row.genres.flatMap(m => m)] you are saying out_data[['Action','Crime']] (for example).
Object keys have to be a string so at this point it converts that to a comma-separated string (due to type coercion in JS). If you do ['Action','Crime'].toString() in your browser console you'll see what comes out.
You need to iterate the genres in each movie.
const groups = movies.reduce((byGenreMap, currentMovie) => {
const newGenreMap = { ...byGenreMap }
currentMovie.genres.forEach((genre) => {
newGenreMap[genre] = newGenreMap[genre] ? [...newGenreMap[genre], currentMovie] : [currentMovie]
})
return newGenreMap
}, {})
I have this JSON & what I want to do is to make genres like this action|adventure|comedy
{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
my component code snippet
data => {
this.movies = data;
var tempArr= data
var genres;
let genresWithPipe=[];
let len= tempArr.length;
for(var i=0; i<len; i++){
genres=tempArr[i].genres+'|';
// console.log(tempArr[i].genres)
for(var j=0;j<genres.length; j++){
if(j<genres.length-1)
genres[j]= genres[j]+'|';
console.log(genres,data);
//genresWithPipe=genres;
}
}
console.log(this.movies,genres)
}
I have tried to do it with the help of for loop in my component but then when I am displaying it in the html with the help of *ngFor then because it's a local variable,it won't show up. If I store array values in a global variable then the variable only store the last array.
You can use map method in order to achieve your requirement and obtain a more cleaner solution.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
Also, you can use join method in order to obtain the structure action|adventure|comedy with | delimiter.
let array=[{ "id": 1, "key": "deadpool", "name": "Deadpool", "description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.", "genres": [ "action", "adventure", "comedy" ], "rate": 8.6, "length": "1hr 48mins", "img": "assets/images/movie-covers/deadpool.jpg" }, { "id": 2, "key": "we-are-the-millers", "name": "We're the Millers", "description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.", "genres": [ "adventure", "comedy", "crime" ], "rate": 7, "length": "1hr 50mins", "img": "assets/images/movie-covers/we-are-the-millers.jpg" }];
array=array.map(function(item){
item.genres=item.genres.join('|');
return item;
});
console.log(array);
A good solution with Array.map() has been proposed, here is another option with Array.forEach():
const data = [{
"id": 1,
"key": "deadpool",
"name": "Deadpool",
"description": "A former Special Forces operative turned mercenary is subjected to a rogue experiment that leaves him with accelerated healing powers, adopting the alter ego Deadpool.",
"genres": [
"action",
"adventure",
"comedy"
],
"rate": 8.6,
"length": "1hr 48mins",
"img": "assets/images/movie-covers/deadpool.jpg"
},
{
"id": 2,
"key": "we-are-the-millers",
"name": "We're the Millers",
"description": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
"genres": [
"adventure",
"comedy",
"crime"
],
"rate": 7,
"length": "1hr 50mins",
"img": "assets/images/movie-covers/we-are-the-millers.jpg"
}
]
const genres = [];
data.forEach(film => genres.push(film.genres.join("|")));
console.dir(genres);
Note that your data definitely doesn't look like what you put in the code sample, it must be wrapped with [].
I'll start out by saying that I am a pretty new web developer, so I apologize if this is overly basic... I just couldn't find it anywhere on Google. I'm receiving JSON data back from an API call to omdb, and I am unsure how to reference a line in the data Specifically, I am trying to reference the Rotten Tomatoes Value, and this needs to be repeatable for any movie I search. I started by storing the response in JSON and then working through each item I need:
var body = JSON.parse(body);
console.log("Title: " + body.Title);
console.log("Release Year: " + body.Year);
console.log("IMdB Rating: " + body.imdbRating);
console.log("Country: " + body.Country);
console.log("Language: " + body.Language);
console.log("Plot: " + body.Plot);
console.log("Actors: " + body.Actors);
console.log("Rotten Tomatoes Rating: " + body.Ratings.????RottenTomatoes???);
It's just the Rotten Tomatoes Value Line I can't figure out! Everything else works. To clarify, this is just a JSON referencing issue I cannot figure out.
{
"Title": "Anastasia",
"Year": "1997",
"Rated": "G",
"Released": "21 Nov 1997",
"Runtime": "94 min",
"Genre": "Animation, Adventure, Drama",
"Director": "Don Bluth, Gary Goldman",
"Writer": "Susan Gauthier (screenplay), Bruce Graham (screenplay), Bob Tzudiker (screenplay), Noni White (screenplay), Eric Tuchman (animation adaptation)",
"Actors": "Meg Ryan, John Cusack, Kelsey Grammer, Christopher Lloyd",
"Plot": "The last surviving child of the Russian Royal Family joins two con men to reunite with her grandmother, the Dowager Empress, while the undead Rasputin seeks her death.",
"Language": "English, Russian, French",
"Country": "USA",
"Awards": "Nominated for 2 Oscars. Another 10 wins & 21 nominations.",
"Poster": "https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BNGJiNWFlYTMtZTBiZi00ZTVmLWJmZmMtNzEzYzZjNzYzZmRmXkEyXkFqcGdeQXVyNTA4NzY1MzY#._V1_SX300.jpg",
"Ratings": [
{
"Source": "Internet Movie Database",
"Value": "7.1\/10"
},
{
"Source": "Rotten Tomatoes",
"Value": "85%"
},
{
"Source": "Metacritic",
"Value": "59\/100"
}
],
"Metascore": "59",
"imdbRating": "7.1",
"imdbVotes": "94,074",
"imdbID": "tt0118617",
"Type": "movie",
"DVD": "16 Nov 1999",
"BoxOffice": "N\/A",
"Production": "20th Century Fox",
"Website": "N\/A",
"Response": "True"
}
The Rotten tomatoes value is in the 3rd element of the array. Array indexes start at 0. Therefore, what you need is body.Ratings[2].Value.
If the order of the Ratings array is unpredictable, use filter function as below.
//If the order of the source array is unpredictable
//use filter
var rtValue = body.Ratings.filter(function(source) {
return source.Source === "Rotten Tomatoes";
}).Value;
That's because it is an array inside an object. body.Ratings[0]. You are referencing the spot of an array. Definitely look into arrays.
"Ratings": [ { "Source": "Internet Movie Database", "Value": "7.1/10" }, { "Source": "Rotten Tomatoes", "Value": "85%" }, { "Source": "Metacritic", "Value": "59/100" } ]
See the [ square brackets ] Each object inside {} can be referenced with an integer inside [0], [1] etc.
Look at some online tutorials. www.w3schools.com/js is a great place to start
Is there any google/Yahoo/Bing API which gives local business results based on a ZIP/GeoCode of a location? If yes, please let me know.
If Google Maps has such service, please let me know what where do I get a reference regarding that?
Disclosure: I work at SerpApi.
Is there any google/Yahoo/Bing API which gives local business results based on a ZIP/GeoCode of a location?
Yes, you can use SerpApi to get local business results based on ZIP, query, or GPS coordinates: https://serpapi.com/playground?engine=google_maps&q=coffee+Austin+TX+78747&type=search
Sample response
{
"local_results": [
{
"position": 1,
"title": "The Standard Grill",
"data_id": "0x89c259c06677ef37:0x5707f22fe7137aa2",
"gps_coordinates": {
"latitude": 40.7406697,
"longitude": -74.0079042
},
"place_id_search": "https://serpapi.com/search.json?data=%214m5%213m4%211s0x89c259c06677ef37%3A0x5707f22fe7137aa2%218m2%213d40.7406697%214d-74.0079042&engine=google_maps&google_domain=google.com&token=f01cbc346c0db944&type=place",
"rating": 4.1,
"reviews": 840,
"price": "$$$",
"type": "Bar & grill",
"address": "848 Washington St, New York, NY 10014",
"hours": "Open until 11:30 PM",
"phone": "(212) 645-4100",
"website": "http://www.thestandardgrill.com/",
"description": "Trendy, upscale American dining. Trendy, clubby, hotel-set American bistro under the High Line with sidewalk tables & lively bar.",
"editorial_reviews": {
"summary": "Where To Eat On Christmas Day In New York City",
"link": "https://www.forbes.com/sites/melissakravitz/2019/12/13/christmas-dinner-new-york-city/"
},
"thumbnail": "https://lh5.googleusercontent.com/p/AF1QipMGM_4u4iQcrdRZApFFIinDga-cb0rXu79aFxvv=w125-h92-k-no"
},
{
"position": 2,
"title": "Rockmeisha - Sake & Grill",
"data_id": "0x89c259938c3a05cb:0xa1b2fe3b945a853d",
"gps_coordinates": {
"latitude": 40.732638,
"longitude": -74.00237299999999
},
"place_id_search": "https://serpapi.com/search.json?data=%214m5%213m4%211s0x89c259938c3a05cb%3A0xa1b2fe3b945a853d%218m2%213d40.732638%214d-74.00237299999999&engine=google_maps&google_domain=google.com&token=8bcfdeb90a3d1f1a&type=place",
"rating": 4.3,
"reviews": 102,
"price": "$$",
"type": "Tapas restaurant",
"address": "11 Barrow St, New York, NY 10014",
"hours": "Opens at 6:00 PM",
"phone": "(212) 675-7775",
"website": "http://rockmeisha-izakaya.business.site/",
"description": "Japanese drink-&-snack joint. Traditional Japanese drinking establishment pairing its sake & beer with ramen & small plates.",
"editorial_reviews": {
"summary": "25 Exemplary Fried Chicken Dishes Around NYC",
"link": "https://ny.eater.com/maps/nyc-fried-chicken-best"
},
"thumbnail": "https://lh5.googleusercontent.com/p/AF1QipNA8eJZ-VZxHIV43490yYZCnjDbBbYUA9wiH_Lq=w122-h92-k-no"
}
]
}
You can use Node.js wrapper
const { GoogleSearchResults } = require('google-search-results-nodejs')
const client = new GoogleSearchResults("API_KEY")
const parameters = {
engine: "google_maps",
type: "search",
google_domain: "google.com",
q: "NY 10014 grill",
};
function onResponse(data) {
console.log(data.local_results[0])
}
client.json(parameters, onResponse)
If Google Maps has such service, please let me know what where do I get a reference regarding that?
https://serpapi.com/maps-local-results
Google does have that, you can even check few sample implementations:
http://code.google.com/apis/ajaxsearch/local.html