I have json data like this :
{
"people": [
{
"id": "1",
"company": "Blitz",
"fullName": "Chad anderson"
},
{
"id": "2",
"company": "NFZ",
"fullName": "surge bash"
},
{
"id": "3",
"company": "Ultimate Chad Company LLC",
"fullName": "George"
},
{
"id": "4",
"company": "Blitz",
"fullName": "Chad kuton"
},
{
"id": "5",
"company": "NFZ",
"fullName": "piguła"
},
]);
currently I have code like this:
function appendData(data) {
let tblBody = document.getElementById('tableWithContent');
let outPut = '';
data.sort((a,b) => a.company.localeCompare(b.company));
for(let person of data){
outPut += `<tr>
<td></td>
<td>${person.fullName}</td>
<td>${person.company}</td>
</tr>`;
}
tblBody.innerHTML = outPut;
};
I would like to display it in a way that :
Creates html table populated with companies and names of employess, within that company. In a way that if both workers have the same company , they are just displayed within that one company.
However, the code displays , and it displays workers in one column, and companies in another.
I would like to know if there is a neat way to use for example. reduce() method to that.
So when I fetch this data to html it displays all of the people from one company , then all of the people from another company (without displaying the companies of employees each time - if they are from the same company).
Related
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))
I needed assistance in order to work out why the aggregate function is not responding the way I'd expect it to respond. This is a RESTful API service I've designed in which I am trying to connect collections with each other. Please note the following:
Collection: Season
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
Collection: Play
{
"_id": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
},
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
My implemented code in JavaScript
function getTestLookUp(db, collectionName, response, secondCollectionName){
console.log('First collection name: ' + collectionName + '\n' + 'Second collection name: ' + secondCollectionName);
db.collection(collectionName).aggregate([
{
$lookup:
{
from: secondCollectionName,
localField: 'PlayID',
foreignField: '_id',
as: 'requestedDetails'
}
}
]).toArray((err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
response.status(200).json({
'Items': res
});
}
});
}
The response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"requestedDetails": []
}
]
}
The things I've checked so far: the collection names are accurate, the ID is also accurate as I can search it up on the MLabs search feature. I don't understand as to why this is returning a empty 'requestedDetails' as I hoped it would return the item from the Play collection.
In addition to this, I would also appreciate if someone can point out how I can join multiple collections instead of 2.
I welcome any questions regarding this problem.
While still researching for this issue, I accidentally came across a another problem in which someone wrote a comment stating that "you might be comparing a String with ObjectID". This was the cause for this error as I obtain a String variable in return from the database and I am comparing the String variable with the _id which is expecting to see a ObjectID variable to complete the query. Therefore, meaning that my query/lookup is never matching these two variables.
The only way tackle this issue is to do a conversion (string to ObjectID) and then compare the values. However, since I'm using the version of ^3.1.10 of MongoDB, this functionality is not possible. Will need to update the version to 4.0 to be able to implement this functionality.
In order to rectify this issue, I managed to surround the foreign ID within $iod tags.
Before
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
After
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
}
}
Response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"Details": [
{
"_id": "5c0fc4aafb6fc04dd6ea4d81",
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
]
}
]
}
This question might not even be related to angularjs and the solution could be plain old js or jquery. But that is what i what to find out.
I want to implement a delete functionality for a particular user and i am wondering if there is a easier way to do this in angularjs or should it be plain old JS?
i have a fairly complex object for eg (going up to 4 levels):
{
"Department": [
{
"Name": "Accounting",
"users": [
{
"id": "1",
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"id": "2",
"firstName": "Mary",
"lastName": "Smith",
"age": 32
}
]
},
{
"Name": "Sales",
"users": [
{
"id": "3",
"firstName": "Sally",
"lastName": "Green",
"age": 27
},
{
"id": "4",
"firstName": "Jim",
"lastName": "Galley",
"age": 41
}
]
}
]
}
this is displayed in a ng-repeat where we should Department and username. If I want to delete a particular user i make an api call and on success of it, I want to delete that object. so i have a js method like this
function DeleteUser(user) {
$.each(ctrl.UserData, function(index, value) {
var filteredPeople = value.filter((item) => item.id !== user.id);
});
The question I have is, if i want to delete this object is there any easier way to delete from model since i have the object here or i have to do the classic jquery way of using like $.grep or filter to iterate through each object and match by id and then delete it?
Presumably, you're iterating over the departments (accounting, sales) in your template, and then over the users in that department.
So you could have, in your template:
<button ng-click="deleteUser(user, department)">...</button>
And the method could thus be as simple as
$scope.deleteUser = function(user, department) {
// delete user from backend, then
department.users.splice(departments.users.indexOf(user), 1);
}
If you really don't want to pass the department, then loop over the departments, and use the above if departments.users.indexOf(user) returns a value that is >= 0.
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.
department {
"_id": "1",
"department": "Computers",
"type": "Department",
"room_no": "102",
"HOD": "Mr. G Rahul",
"floor": "1st Floor"
}
student {
"_id": "fdf370e2f43d4af1b505b8913502a5e4",
"_rev": "1-16df9a4cd45ca69009ab6c9767425a8e",
"student Name": "H Ravi",
"date_of_birth": "March 1, 1993",
"roll_no": "55",
"inter_marks": "820",
"secondary_marks": "420"
"department_id": "1",
"type": "student"
}
Map Function
function(doc) {
var id,department,student,hod,dob;
if(doc.type == 'student') {
id = doc.department_id;
dob = new Date(doc.date_of_birth)
student = doc;
}
}
emit(dob, {'_id': id,"student_doc": student});
}
After writing map function we call view by using URL "//localhost:5984/db_name/_design/design_name/_view/view_name". In that URL we will append ?include_docs=true after "view_name"("//localhost:5984/db_name/_design/design_name/_view/view_name/?include_docs=true") to get the docs of by using _id in emit, example: emit(dob,{"_id": id}) it will return the docs of linked id...My question is how can we access that docs in reduce function.
You can’t, the docs are fetched on query time, not on indexing time, so the reduce function never gets to see that data. Sorry!