Object.values filter on 'keypress' - javascript

As I'm using this technique to get dummy data from SWAPI.
const httpStarwars$ = createHttpObservables('https://swapi.dev/api/films/');
fromEvent<any>(this.sTxt.nativeElement,'keypress').pipe(
map(event => event.target.value),
debounceTime(400),
distinctUntilChanged(),
switchMap(val => httpStarwars$.pipe(
map(res => Object.values(res["results"]))
))
).subscribe(courses => console.log(courses));
Here is the expected result after key press.
0: {title: "A New Hope", episode_id: 4, opening_crawl: "It is a period of civil war.
↵Rebel spaceships, st…er
↵people and restore
↵freedom to the galaxy....", director: "George Lucas", producer: "Gary Kurtz, Rick McCallum", …}
1: {title: "The Empire Strikes Back", episode_id: 5, opening_crawl: "It is a dark time for the
↵Rebellion. Although the… remote probes into
↵the far reaches of space....", director: "Irvin Kershner", producer: "Gary Kurtz, Rick McCallum", …}
2: {title: "Return of the Jedi", episode_id: 6, opening_crawl: "Luke Skywalker has returned to
↵his home planet of…
↵struggling to restore freedom
↵to the galaxy...", director: "Richard Marquand", producer: "Howard G. Kazanjian, George Lucas, Rick McCallum", …}
3: {title: "The Phantom Menace", episode_id: 1, opening_crawl: "Turmoil has engulfed the
↵Galactic Republic. The t…ustice in the
↵galaxy, to settle the conflict....", director: "George Lucas", producer: "Rick McCallum", …}
4: {title: "Attack of the Clones", episode_id: 2, opening_crawl: "There is unrest in the Galactic
↵Senate. Several t…THE REPUBLIC
↵to assist the overwhelmed
↵Jedi....", director: "George Lucas", producer: "Rick McCallum", …}
5: {title: "Revenge of the Sith", episode_id: 3, opening_crawl: "War! The Republic is crumbling
↵under attacks by t…ate mission to rescue the
↵captive Chancel
Now I want to filter the result of the above data below using filters.
map(res => Object.values(res["results"]))
What I will filter is title. So far what I used is this technique below.
map(res => Object.values(res["results"]).filter(j => j["title"] == res))
It gave me empty array like this [].
UPDATE 1:
Update 2:

Update 1
I edit my answer to use Typescript.
I think that what you want to do is just filter your response by title, so you can just do that:
interface Movie {
title: string;
episode_id: number;
}
const res = {};
res["results"] = {
0: {title: "A New Hope", episode_id: 4},
1: {title: "The Empire Strikes Back", episode_id: 5 },
2: {title: "Return of the Jedi", episode_id: 6},
3: {title: "The Phantom Menace", episode_id: 1},
4: {title: "Attack of the Clones", episode_id: 2}
}
const result = Object.values(res["results"]).filter((movie: Movie) => movie.title === "A New Hope")
console.log(result)
Just remember to verify before if res["results"] contains the object with the movies.

Related

Is there a way to format a JavaScript object logged to console in vscodes integrated git bash terminal?

I'm currently working with a an object and loading it into the terminal console with console.log(books)
The code for the object is this.
const books = [
{
id:1,
name: "Harry Potter and the Chamber of Secrets",
authorId: 1
},
{
id: 2,
name: "Harry Potter and the Prisoner of Azkaban",
authorId: 1
},
{
id: 3,
name: "Harry Potter and the Goblet of Fire",
authorId: 1
},
{
id: 4,
name: "The Fellowship of the Ring",
authorId: 2
},
{
id: 5,
name: "The Two Towers",
authorId: 2
},
{
id: 6,
name: "The Return of the King",
authorId: 2
},
{
id: 7,
name: "The Way of Shadows",
authorId: 3
},
{
id: 8,
name: "Beyond the Shadows",
authorId: 3
},
];
It's quite a small problem, but I've noticed that not all of the information is displayed consistently when I log to console. Is this a problem with the git bash terminal or the integration between vscode and git bash and is there anything that can be done to make the presentation more consistent? It's a bit jarring.
I've tried looking for resources on this issue and haven't found anything similar. Would be great to get ideas as even if it's a small thing, when looking through larger data sets, it would be nice to know it will be formatted consistently.
I found a great answer to this on Handy Tips on Using Console Log
You can use Stringify to structure big objects and create consistent formatting.
If I type the following it formats nicely.
console.log(JSON.stringify(books, null, 2))

Cant parse a dictionary retrieved from xmlhttprequest.responseText [SOLVED]

In my program, I make a call to my python script to return a dictionary. I am trying to access this dictionary in JavaScript after completing the XMLHttpRequest. response text. The dictionary will appear however, I am not able to parse it.
For example: calling this,responseText['Username']; returns undefined
I have tried stringifying the responseText and then parsing it, which hasn't helped at all. What am I doing wrong? I have been stuck on this for too long
Requested function:
def getBasicInfo():
dict = {}
list = []
username = ud["username"]
displayName = ide["displayName"]
accountCreationDate = ud['creationTime']
following = fol["followingUsersCount"]
followers = fol['followerCount']
playlistCount = len(ply["playlists"])
playlists = ply["playlists"]
dict.update({"Username": username})
dict.update({"Display Name": displayName})
dict.update({"Account Creation Date": accountCreationDate})
dict.update({"Following": str(following)})
dict.update({"Followers": str(followers)})
dict.update({"Number of playlists": str(playlistCount)})
for x in range(0, len(ply["playlists"])):
list.append(playlists[x]["name"])
dict.update({"Playlist names": list})
totalNumberSongs = len(sh1) + len(sh2) + len(sh3)
firstTime = sh1[0]['endTime']
lastTime = sh3[-1]['endTime']
dict.update({"Total Number of Songs Analyzed": str(totalNumberSongs)})
timeStamp = firstTime + " to " + lastTime
dict.update({"Data Lifecycle": timeStamp})
return dict
Python Script:
#!\Users\bobs\anaconda3\python.exe #Python Interpreter
from data import *
import cgi
import sys
fs = cgi.FieldStorage()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
if "basic" in fs.keys():
info = getBasicInfo()
print(info)
if "artist" in fs.keys():
artist = countArtistsDesc()
print(artist)
if "song" in fs.keys():
song = countSongsDesc()
print(song)
if "day" in fs.keys():
day = getHighestPlayedDays(True)
print(day)
if "playlist" in fs.keys():
playlist = getPlaylist()
print(playlist)
sys.stdout.write("\n")
sys.stdout.close()
HTML Page/XMLHTTPRequest:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basic Info</title>
</head>
<body style="background-color:#1DB954">
<h1 align="center">User's Basic Info</h1>
<script>
var http = new XMLHttpRequest();
http.open('GET', '/cgi-bin/simpleData.py?basic=True', true);
http.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
// http.responseType = 'json'
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("responseText").innerHTML = this.responseText;
document.getElementById("problem").innerHTML = this.responseText['Username'];
}
};
http.send(null);
</script>
<p id="responseText"></p>
<p id="problem"></p>
</body>
</html>
Output:
{'Username': 'bobsmith123', 'Display Name': 'Bob Smith', 'Account Creation Date': '2016-10-10', 'Following': '34', 'Followers': '46', 'Number of playlists': '32', 'Playlist names': ['5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party 🍻', 'Rap', 'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies', 'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020', 'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour', 'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP", 'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld 🎢🎡🎠', 'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'], 'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'}
undefined
Solution:
#Very end of getBasicInfo()
return json.dumps(dict, separators=(',', ':'))
#After readyState == 4 && this.status == 200 in the HTML page
parsed = JSON.parse(this.responseText);
This is because python represents strings with single quotes, and json requires double quotes.
import json;
body = {'Username': 'bobsmith123', 'Display Name': 'Bob Smith',
'Account Creation Date': '2016-10-10', 'Following': '34',
'Followers': '46', 'Number of playlists': '32',
'Playlist names': [
'5th Dimension', 'Dumb Chilling', 'Rock v2 / Nu Metal', 'Party 🍻', 'Rap',
'Pumping Iron', 'Aggression', 'Soundcloud 4', 'Oldies but Goodies',
'Chopped and Screwed', 'Cruel Winter', 'Soundcloud', 'Halloween 2020',
'Trap Christmas', "80's Night", 'EDM', 'Life of Pablo Tour', 'Igor Tour',
'Thugger', 'Playboi Carti', 'Cactus Jack', "WAKE UP MR WEST, OH HE'S UP",
'Future', 'Denzel', 'LORDE PRETTY FLACKO JOYDE', 'AstroWorld 🎢🎡🎠',
'Daytona Tour', 'Children of the Korn', 'Rock', 'Classics', 'Floyd', 'Chill Rock'],
'Total Number of Songs Analyzed': '27334', 'Data Lifecycle': '2020-01-24 19:37 to 2021-01-25 20:52'
}
print(json.dumps(body))
That produces the output in the correct format
{"Username": "bobsmith123", "Display Name": "Bob Smith", "Account Creation Date": "2016-10-10", "Following": "34", "Followers": "46", "Number of playlists": "32", "Playlist names": ["5th Dimension", "Dumb Chilling", "Rock v2 / Nu Metal", "Party \ud83c\udf7b", "Rap", "Pumping Iron", "Aggression", "Soundcloud 4", "Oldies but Goodies", "Chopped and Screwed", "Cruel Winter", "Soundcloud", "Halloween 2020", "Trap Christmas", "80's Night", "EDM", "Life of Pablo Tour", "Igor Tour", "Thugger", "Playboi Carti", "Cactus Jack", "WAKE UP MR WEST, OH HE'S UP", "Future", "Denzel", "LORDE PRETTY FLACKO JOYDE", "AstroWorld \ud83c\udfa2\ud83c\udfa1\ud83c\udfa0", "Daytona Tour", "Children of the Korn", "Rock", "Classics", "Floyd", "Chill Rock"], "Total Number of Songs Analyzed": "27334", "Data Lifecycle": "2020-01-24 19:37 to 2021-01-25 20:52"}
and as a bonus you get escaped unicode characters.

Trying to console.log properties from an Express/Mongo api, using a React.js frontend

I'm putting together a very simple fictional sneaker app, using the MERN stack.
I wouldn't call myself a newbie, but I'm not an expert either. I was able to create the backend just fine and generate a json rest-api. My problem is on the front-end. I'm simply trying to console.log a property from an object.
For example, I have a route that gets an array of sneaker objects. In each object, it contains info such as the Sneaker Model, Colorway, Year the sneaker was released, here a preview of the object.
{
"_id": "5c5dff42489e28576c28cd9e",
"model": "Air Jordan 11",
"colorway": "Win Like 82",
"year": 1997,
"text": "Cool kicks",
"mainimage": "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664062/xjwkpbqwl1pmawpocygx.jpg",
"subimage_1": "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664062/y8h1biytup4rgxqrm2qe.jpg",
"subimage_2": "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664063/wrwska4tnog4vselcwp7.jpg",
"subimage_3": "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664063/h9dyki3gdgfjcccchhia.jpg",
"subimage_4": "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664064/qwrsabomnsqk7pjyx5ss.jpg",
"user": "5c4b4635c9de365620cd797b",
"likes": [],
"comments": [],
"date": "2019-02-08T22:14:26.127Z",
"__v": 0
}
I use destructuring to get the sneaker data from my application (Redux) state:
const { sneakers } = this.props.sneaker;
When I try to console.log the array of objects using console.log(sneakers) it works as expected these are the results:
(3) [{…}, {…}, {…}]
0:
colorway: "Win Like 82"
comments: []
date: "2019-02-08T22:14:26.127Z"
likes: []
mainimage: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664062/xjwkpbqwl1pmawpocygx.jpg"
model: "Air Jordan 11"
subimage_1: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664062/y8h1biytup4rgxqrm2qe.jpg"
subimage_2: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664063/wrwska4tnog4vselcwp7.jpg"
subimage_3: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664063/h9dyki3gdgfjcccchhia.jpg"
subimage_4: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549664064/qwrsabomnsqk7pjyx5ss.jpg"
text: "Cool kicks"
user: "5c4b4635c9de365620cd797b"
year: 1997
__v: 0
_id: "5c5dff42489e28576c28cd9e"
__proto__: Object
1:
colorway: "taxi"
comments: []
date: "2019-02-08T19:20:59.467Z"
likes: []
mainimage: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653655/gag2aktdhyfru5s5dnni.jpg"
model: "Air Jordan 12"
subimage_1: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653656/wcg9jmo84cl8mhxb2iwl.jpg"
subimage_2: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653656/mxistpujhh0xikzqwcu0.jpg"
subimage_3: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653657/dcp1y2jrqz2nkgyhuwfr.jpg"
subimage_4: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653657/dyee9uzb7aj1dp46rlnj.jpg"
text: "the holy grails"
user: "5c4b4635c9de365620cd797b"
year: 1997
__v: 0
_id: "5c5dd69beaef7140e0d2926d"
__proto__: Object
2:
colorway: "Obsidian"
comments: []
date: "2019-02-03T23:01:21.937Z"
likes: []
mainimage: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549234878/yzdoot1cf3jnbq31ndkg.jpg"
model: "Air Jordan 12"
subimage_1: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549234879/jbjw8hngvieyvnizfb8b.jpg"
subimage_2: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549234880/qu1gguxpfp2mapd5ivo2.jpg"
subimage_3: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549234880/gcntdjlznjjbxifsmufl.jpg"
subimage_4: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549234881/ck9emeurmaqleizaqe1e.jpg"
text: "Awesome kicks"
user: "5c4b4553c9de365620cd797a"
year: 1997
__v: 0
_id: "5c5772c10ffd0f2e789999b2"
__proto__: Object
length: 3
__proto__: Array(0)
If I want to say for instance just the second sneaker I use:
console.log(sneakers[1])
I get what I expected:
{_id: "5c5dd69beaef7140e0d2926d", model: "Air Jordan 12", colorway: "taxi", year: 1997, text: "the holy grails", …}
colorway: "taxi"
comments: []
date: "2019-02-08T19:20:59.467Z"
likes: []
mainimage: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653655/gag2aktdhyfru5s5dnni.jpg"
model: "Air Jordan 12"
subimage_1: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653656/wcg9jmo84cl8mhxb2iwl.jpg"
subimage_2: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653656/mxistpujhh0xikzqwcu0.jpg"
subimage_3: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653657/dcp1y2jrqz2nkgyhuwfr.jpg"
subimage_4: "http://res.cloudinary.com/dwgjvssdt/image/upload/v1549653657/dyee9uzb7aj1dp46rlnj.jpg"
text: "the holy grails"
user: "5c4b4635c9de365620cd797b"
year: 1997
__v: 0
_id: "5c5dd69beaef7140e0d2926d"
__proto__: Object
However, when I try to get a property from just one sneaker, let's say for example the colorway from the second sneaker I use:
console.log(sneakers[1].colorway)
And I run into this error TypeError: Cannot read property 'colorway' of undefined.
I'm a little hard pressed to figure out why. I figured since I can log data from one sneaker if I wanted to I should be able to log just one property from that sneaker. Obviously, there is something that I'm not doing quite right, but I can't figure out what.
Most likely, the data object prints as a browser-level convenience but is not actually ready for property access. To circumvent this problem, I've used this pattern with success:
const SomeComponent = ({sneakers}) => {
return (
<div>
{
sneakers && sneakers.map(sneaker => {
return (
<div>{sneaker.colorway}</div>
)
})
}
</div>
)
}
export default SomeComponent;

How do I turn this array of objects into a string using ES6 methods?

I have the following array of objects:
const pagesByBook = [
{bookName: "An old tome", pages: 123},
{bookName: "Really ancient stuff", pages: 432},
{bookName: "Yup, another old book", pages: 218}
]
And I would like to get the following string output:
const output= "['An old tome', 123, 'old', null],
['Really ancient stuff', 432, 'old', null],
['Yup, another old book', 218, 'old', null]"
How can I do this using in a few lines using ES6 methods such as map?
This seems to me to be a simple map with ES6 destructuring. Assuming that the last 2 elements in the arrays are constants (old, null):
const data = [ {bookName: "An old tome", pages: 123}, {bookName: "Really ancient stuff", pages: 432}, {bookName: "Yup, another old book", pages: 218} ]
const result = data.map(({bookName, pages}) => [bookName, pages, 'old', null])
console.log(JSON.stringify(result))
If a string representation of this is needed you could change it to:
const data = [ {bookName: "An old tome", pages: 123}, {bookName: "Really ancient stuff", pages: 432}, {bookName: "Yup, another old book", pages: 218} ]
const result = data.map(({bookName, pages}) => JSON.stringify([bookName, pages, 'old', null]))
console.log(result.join(','))
Use JSON.stringify, Array#map, Object.values, Array#slice and Array#concat to get your required result.
const pagesByBook = [{
bookName: "An old tome",
pages: 123
},
{
bookName: "Really ancient stuff",
pages: 432
},
{
bookName: "Yup, another old book",
pages: 218
}
]
const res = JSON.stringify(pagesByBook.map(item => Object.values(item).concat("old", null))).slice(1, -1);
console.log(res)

Generate a JSON file from keyless list in Python

I've been doing some web-scraping recently and ultimately fetched the data I wanted. However, there is no sense of organization since it's only a simple list in Python. It contains the meeting type (either LE/DI/SE), days, time, professor's name (edited for privacy), among some other values.
["LE", "A00", "MWF", "10:00a-10:50a", "MLK", "AUD", "Smith, John", "976539", "DI", "A01", "F", "5:00p-5:50p", "MLK", "AUD", "Smith, John", "FULL Waitlist(25)", "216", "FI", "03/17/2018", "S", "8:00a-10:59a", "TBA", "TBA", "LE", "B00", "MWF", "1:00p-1:50p", "WLH", "2005", "Smith, John", "927471", "DI", "B01", "F", "6:00p-6:50p", "MLK", "AUD", "Smith, John", "FULL Waitlist(32)", "200", "FI", "03/17/2018", "S", "8:00a-10:59a", "TBA", "TBA"]
As you can see, it's an ugly list. My goal is to make it something like this:
{
"MATH101": {
"LE": {
sectionCode: 'A00',
days: 'MFW',
times: '10:00a-10:50am',
building: 'MLK',
room: 'AUD',
instructor: 'Smith, John',
"DI": {
sectionCode: 'A01',
days: 'F',
times: '5:00-5:50pm',
building: 'MLK',
room: 'AUD',
instructor: 'Smith, John',
availableSeats: 'FULL Waitlist(25)',
capacity: '216'
}
},
"LE": {
sectionCode: 'B00',
days: 'MFW',
times: '1:00a-1:50pm',
building: 'MLK',
room: 'AUD',
instructor: 'Smith, John',
"DI": {
sectionCode: 'B01',
days: 'F',
times: '6:00-6:50pm',
building: 'MLK',
room: 'AUD',
instructor: 'Smith, John',
availableSeats: 'FULL Waitlist(32)',
capacity: '200'
}
}
}
}
There is a discussion per lecture section, thus there are two lecture times and two discussions that pertain to each lecture. I don't know if there is a better schema to store this data, but I could only come up with this.
I thought iterating through the list and saving values starting after the "LE" or "DI" strings into the ordered way that I established above, but I don't see how that would help me create the json file without each key.
I'm new to all this, and I haven't been able to find a solution. Tried converting into dictionary but it doesn't meet my needs. A lot of data is also repeated, such as the professor's name, but there won't always be one professor, nor two lectures/discussions. I plan to do this with all the courses available, so this just gets more and more complicated...
Hopefully someone is able to help out, thank you!

Categories

Resources