Formatting JSON data retrieved from PostgreSql database - javascript

I am trying to display my seed data as JSON when a user visits a certain endpoint. I have two tables, Playlists and Favorites. It is a one to many relationship where a Playlist has many Favorites. The JSON should be formatted like this:
[{
"id": 1,
"playlist_name": "Favorite songs of all time",
"favorites": [{
"id": 1,
"name": "We Will Rock You",
"artist_name": "Queen",
"genre": "Rock",
"rating": 88
}]
}]
The function that I am calling to retrieve data from the database is this:
const connection = require("../connection");
function getAll() {
return connection.select().from('playlists').join('favorites', 'playlists.id', '=', 'favorites.id')
}
module.exports = getAll;
And what I get back when I call this function is this:
[
{
"id": 1,
"playlist_name": "chill_tunes",
"name": "Leo",
"artist_name": "John",
"genre": "Pop",
"rating": 42,
"playlist_id": 1
},
{
"id": 2,
"playlist_name": "good_vibes",
"name": "Dan",
"artist_name": "Deer",
"genre": "Rock",
"rating": 52,
"playlist_id": 1
},
{
"id": 3,
"playlist_name": "hump_day_happiness",
"name": "Nick",
"artist_name": "Legend",
"genre": "Rap",
"rating": 12,
"playlist_id": 2
}
]
I have no idea how to format my JSON data to get it like the code up top. Any help would be greatly appreciated.

You can use reduce
Here idea is
On op object create keys based on playlist id.
If there's already a key we push the new value to favourites
If not than we initialize favourites with {id, playlist_name , favourites:[]} and than push the new value
let arr = [{"id": 1,"playlist_name": "chill_tunes","name": "Leo","artist_name": "John","genre": "Pop","rating": 42,"playlist_id": 1},{"id": 2,"playlist_name": "good_vibes","name": "Dan","artist_name": "Deer","genre": "Rock","rating": 52,"playlist_id": 1},{"id": 3,"playlist_name": "hump_day_happiness","name": "Nick","artist_name": "Legend","genre": "Rap","rating": 12,"playlist_id": 2}]
let final = arr.reduce((op,{id, playlist_name ,name ,artist_name ,genre ,rating , playlist_id}) => {
op[playlist_id] = op[playlist_id] || {id, playlist_name , favourites:[]}
op[playlist_id].favourites.push({id, playlist_id ,name ,artist_name ,genre ,rating})
return op
},{})
console.log(Object.values(final))

Related

How can I store mapping orders in BBDD and then eval them

I'm trying to store in MongoDB one document with an object with the properties I want to map latter. My idea it's to create a function that will receive 2 params. First the object where I got to find the mapping, and second the object where I have to take the info from.
For example I want to store this JSON (that would be the first parameter in the function):
{
"name": "client.firstName",
"surname": "client.surname",
"age": "client.age",
"skills": [
{
"skillName": "client.skills[index].name",
"level": "client.skills[index].levelNumber",
"categories": [
{
"categoryName": "client.skills[index].categories[index].name",
"isImportant": "client.skills[index].categories[index].important"
}
]
}
]
}
And the second paramenter would be something like this (it's the object where you find the information.
{
"client": {
"firstName": "Jake",
"surname": "Long",
"age": 20,
"skills": [
{
"name": "Fly",
"level": 102,
"categories": [
{
"name": "air",
"important": true
},
{
"name": "superpower",
"important": false
}
]
},
{
"name": "FastSpeed",
"level": 163,
"categories": [
{
"name": "superpower",
"important": false
}
]
}
]
}
}
The idea it's: with de paths that I have in the first object, find it in the second one.. The problem I found it's when I have arrays, because when I defined the mapping rules I don't know how many positions will have the array I want to map. So in the mapping object (first) I'll only define the path but I'll not put it with the same lenght of the secondone because I don't know how much it will have.

How can I pull a key value from JSON API only if another key name within the group matches?

So this is whats on the JSON file:
{
"page": 1,
"total_pages": 10,
"listings": [
{
"name": "Bob",
"occu": "Entry",
"team": "Blue",
"sec": 3,
"days": 16
},
{
"name": "Tom",
"occu": "Advance",
"team": "Main",
"sec": 1,
"days": 23
},
This continues on with hundreds of other entries...
How can I pull the value of "days" only if the "name" is Tom for example.
Sorry if this is a primitive question, im just getting started on developing and im working on a quick project that will help my local sports team and im quite not that advanced with scripting or APIs. Thanks
To pull the value of "days" only if the "name" is Tom need to filter by'Tom' name and then map days
let listings = [
{
"name": "Bob",
"occu": "Entry",
"team": "Blue",
"sec": 3,
"days": 16
},
{
"name": "Tom",
"occu": "Advance",
"team": "Main",
"sec": 1,
"days": 23
},
{
"name": "Tom",
"occu": "Advanddce",
"team": "Maiddn",
"sec": 1,
"days": 55
}
];
const result = listings.filter(listing=> listing.name=="Tom").map(listing => listing.days);
console.log(result);
You can make a function like this which loops through an array (listings) of objects:
getDaysFromListings = (listings, name) => {
for (let listing of jsonObj.listings) {
if (listing.name === name) {
return listing.days;
}
}
// didn't find 'Tom', return empty string
return '';
}
Then, call your function like this:
// assuming your entire json object is stored in a variable called "json"
let days = getDaysFromListings(json.listings, 'Tom');
Since your variable days comes as a string, you can turn this into a number with +days.
Edit: To add the variable days to html, first, let's assume you want to add the text to a div that looks like this:
<div id="target"></div>
You can use javascript to add the days variable here like this:
// assume you already stored the data in variable
document.getElementById('target').innerHTML = days;
Note: You have to load this javascript after you load the html div above.
As there are many ways to achieve this and am certain this may not be the best method, one way is using Array.prototype.find
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
var array1 = [{
"name": "Bob",
"occu": "Entry",
"team": "Blue",
"sec": 3,
"days": 16
}, {
"name": "Tom",
"occu": "Advance",
"team": "Main",
"sec": 1,
"days": 23
}];
var found = array1.find(function(element) {
return element.name === "Bob";
});
console.log(found.days);

Append '|' after every array element

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 [].

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Dojox Json Query expressions

I am using Dojox to get an array of objects back that meet an expression, I recently changed my service and now it returns more complicated JSON property banes and my query has stopped working. I think I can place a wild card [*]operator to the start of my query string.
Old JSON
[
{
"attributes": [{
"Type": 1,
"User": "Dave",
"Location": "England"
}]
},
{
"attributes": [{
"Type": 1,
"User": "Paul",
"Location": "England"
}]
},
{
"attributes": [{
"Type": 2,
"User": "James",
"Location": "England"
}]
}
]
Old query string
var jam = dojox.json.query(“[?attributes.Type='0'”, data);
This used to work fine but since the JSON has changed the query isn't working
New JSON
[
{
"attributes": [{
somevalue."sometingelse".username.Type: 1,
somevalue."sometingelse".username.User: "Dave",
somevalue."sometingelse".username.Location: "England",
}]
},
{
"attributes": [{
somevalue."sometingelse".username.Type: 1,
somevalue."sometingelse".username.User: "Paul",
somevalue."sometingelse".username.Location: "England",
}]
},
{
"attributes": [{
somevalue."sometingelse".username.Type: 2,
somevalue."sometingelse".username.User: "Steve",
somevalue."sometingelse".username.Location: "England",
}]
}
]
I have tried with a few variations of a similar query with no success
var jam = dojox.json.query(“[?attributes.*Type='0'”, data);
var jam = dojox.json.query(“[?attributes][*Type='0']”, data);
Happy to give further details, thank you in advance.
Essentially a dodgy join we replaced it with a view and set the field names. Another fix was to rename all the layers in the MXD and republished the ArcGIS service.
var jam = dojox.json.query(“[?attributes.Type='0'”, data);
Would work fine after that.

Categories