Manipulate json data to fit in tree data table in ant design - javascript

I need to manipulate my API called data to a certain format to show in ant design table (tree data). https://ant.design/components/table/#components-table-demo-tree-data
However, I spent hours and still cannot figure out how I can manipulate the data from API to display in the required format. Below is an example if I am grouping the information based on the projectId.
Each tree will show the projectId, then the information within the tree (the children), will display all the information of the people who is in that project. If a person is in multiple project, then the information will be in all the project that she exist in.
Can anyone please help me on this. How can I manipulate the data to achieve this?
Object gotten from API call that needs to be manipulated:
{
"data": [
{
"email": "alyssayo#xxx.com",
"permissionIds": null,
"roleIds": ["raa","baa","caa"],
"projectIds": ["1aa","3aa"]
},
{
"email": "chiuewww#xxx.com",
"permissionIds": null,
"roleIds": ["baa","caa"],
"projectIds": ["1aa","2aa","3aa"]
},
{
"email": "lalaqq#xxx.com",
"permissionIds": null,
"roleIds": ["caa"],
"projectIds": ["1aa"]
}
],
"statusCode": 200,
"succeeded": true,
"code": "",
"message": "",
"additionalInfo": null
}
After manipulation, the data should look something like this:
const data = [
{
projectIds: "1aa",
children: [
{
email: "alyssayo#xxx.com",
permissionIds: null,
roleIds: ["raa","baa","caa"],
projectIds: "1aa",
},
{
email: "chiuewww#xxx.com",
permissionIds: null,
roleIds: ["baa","caa"],
projectIds: "1aa",
},
{
email: "lalaqq#xxx.com",
permissionIds: null,
roleIds: ["caa"],
projectIds: "1aa",
}
]
},
{
projectIds: "2aa",
children: [
{
email: "chiuewww#xxx.com",
permissionIds: null,
roleIds: ["baa","caa"],
projectIds: "2aa",
}
]
},
{
projectIds: "3aa",
children: [
{
email: "alyssayo#xxx.com",
permissionIds: null,
roleIds: ["raa","baa","caa"],
projectIds: "3aa",
},
{
email: "chiuewww#xxx.com",
permissionIds: null,
roleIds: ["baa","caa"],
projectIds: "3aa",
}
]
}
];
How the table should look like (another example with different attributes and structure):
Code for the example of how the tree table works:
https://codesandbox.io/s/antd-tree-table-forked-qc995o?file=/index.js

It looks like you just want to do a transformation. In this case you might consider the below solution which uses Array#map and Array#reduce to output the format you need.
UPDATED SOLUTION
const projectIdToChildrenDict = apiData.reduce((dict, item) => {
item.projectIds.forEach(projectId => {
if (dict[projectId] === undefined) {
// instantiate empty array if the project id key is not found
dict[projectId] = [];
}
dict[projectId].push(item);
});
return dict;
}, {})
const data = Object.keys(projectIdToChildrenDict).map(key => {
return {
projectIds: key,
children: projectIdToChildrenDict[key]
}
})
It's not a full solution, but it should get you 90% there.
The first section projectIdToChildrenDict is using Array#reduce to build an object. This object is like a dictionary (hence the name) where you can look up a projectId and see all of the elements that contained that project Id.
Then when we are initializing data we are iterating over the previously built dictionary's keys (project ids) using Array#map and returning a new object of the expected output.

Related

Aggregating the result of the MongoDB model query

I have a model Book with a field "tags" which is of type array of String / GraphQLString.
Currently, I'm able to query the tags for each book.
{
books {
id
tags
}
}
and I get the result:
{
"data": {
"books": [
{
"id": "631664448cb20310bc25c89d",
"tags": [
"database",
"middle-layer"
]
},
{
"id": "6316945f8995f05ac71d3b22",
"tags": [
"relational",
"database"
]
},
]
}
}
I want to write a RootQuery where I can fetch all unique tags across all books. This is how far I am (which is not too much):
tags: {
type: new GraphQLList(GraphQLString),
resolve(parent, args) {
Book.find({}) // CAN'T FIGURE OUT WHAT TO DO HERE
return [];
}
}
Basically, I'm trying to fetch all books and then potentially merge all tags fields on each book.
I expect that if I query:
{
tags
}
I would get
["relational", "database", "middle-layer"]
I am just starting with Mongoose, MongoDB, as well as GraphQL, so not 100% sure what keywords to exactly look fo or even what the title of this question should be.
Appreciate the help.
You want to $unwind the arrays so they're flat, at that point we can just use $group to get unique values. like so:
db.collection.aggregate([
{
"$unwind": "$data.books"
},
{
"$unwind": "$data.books.tags"
},
{
$group: {
_id: "$data.books.tags"
}
}
])
Mongo Playground
MongoDb + JavaScript Solution
tags = Book.aggregate([
{
$project: {
tags: 1,
_id: 0,
}
},
])
This returns an array of objects that contain only the tags value. $project is staging this item in the aggregation pipeline by selecting keys to include, denoted by 1 or 0. _id is added by default so it needs to be explicitly excluded.
Then take the tags array that looks like this:
[
{
"tags": [
"database",
"middle-layer"
]
},
{
"tags": [
"relational",
"database"
]
}
]
And reduce it to be one unified array, then make it into a javascript Set, which will exclude duplicates by default. I convert it back to an Array at the end, if you need to perform array methods on it, or write back to the DB.
let allTags = tags.reduce((total, curr) => [...total, ...curr.tags], [])
allTags = Array.from(new Set(allTags))
const tags = [
{
"tags": [
"database",
"middle-layer"
]
},
{
"tags": [
"relational",
"database"
]
}
]
let allTags = tags.reduce((total, curr) => [...total, ...curr.tags], [])
allTags = Array.from(new Set(allTags))
console.log(allTags)
Pure MongoDB Solution
Book.aggregate([
{
$unwind: "$tags"
},
{
$group: {
_id: "_id",
tags: {
"$addToSet": "$tags"
}
}
},
{
$project: {
tags: 1,
_id: 0,
}
}
])
Steps in Aggregation Pipeline
$unwind
Creates a new Mongo Document for each tag in tags
$group
Merges the individual tags into a set called tags
Sets are required to be have unique values and will exclude duplicates by default
_id is a required field
_id will be excluded from the final aggregation so it doesn't matter what it is
$project
Chooses which fields to pull from the previous step in the pipeline
Using it here to exclude _id from the results
Output
[
{
"tags": [
"database",
"middle-layer",
"relational"
]
}
]
Mongo Playground Demo
While this solution gets the result with purely Mongo queries, the resulting output is nested and still requires traversal to get to desired fields. I do not know of a way to replace the root with a list of string values in an aggregation pipeline. So at the end of the day, JavaScript is still required.

Supabase JSON query JavaScript

Im trying to fetch single entry from my table that contains and JSONB array of objects. Can I match somehow that array to find the desired result?
[
{
"chats": [
{
"id": 56789,
},
{
"id": 66753,
},
],
"id": 999
},
{
"chats": [
{
"id": 43532,
}
],
"id": 999
}
]
I would like to get the object that matches id 999 and contains in chats -> id: 66753
Tried few approaches but none worked.
I though something link this will work.But no success
let { data, error } = await supabase
.from('xyz')
.select('*')
.eq('id', 999)
.contains('chats', {id: 66753})
Can it be done ?
I believe you need to use the ->> operator when querying JSONB data from supabase as noted here in the docs.
So, if your column with the array of objects is titled jsonb, something to the effect of:
let { data, error } = await supabase
.from('xyz')
.select('*')
.eq('id:jsonb->>id', 999)
.contains('chats:jsonb->>chats', ['chats->id: 66753'])
More info can be found on PostgREST docs here

Make CreateQueryBuilder return nested object instead of one flat object

I'm using Typescript with TypeORM. Using CreateQueryBuilder, I want to receive a nested object. Instead I'm receiving a single flat object as represented in block number two. How can I fix this?
const x = await getConnection()
.createQueryBuilder()
.select(['reportHead', 'order', 'workOrder'])
.from('report_head', 'reportHead')
.innerJoin('reportHead.workOrder', 'workOrder')
.innerJoin('workOrder.order', 'order')
.where(`order.customer.id = :customerId`, { customerId: req.user.customer.id })
.execute();
How can I avoid the data looking like this:
{
"reportHead_id": "asd",
"reportHead_number": "123",
"workOrder_id": "dsa",
"workOrder_status: "OK",
"order_id": "sda",
"order_whatev": "ks"
}
but rather have a neste object like this:
{
"reportHead": {
"id": ...
},
"workOrder": {
"id": ...
},
"order": {
"id": ...
}
}
The solution was to not use .execute(), but rather .getMany().

How to get all values of given specific keys (for e.g: name) without loop from json?

I want to fetch all the names and label from JSON without loop. Is there a way to fetch with any filter method?
"sections": [
{
"id": "62ee1779",
"name": "Drinks",
"items": [
{
"id": "1902b625",
"name": "Cold Brew",
"optionSets": [
{
"id": "45f2a845-c83b-49c2-90ae-a227dfb7c513",
"label": "Choose a size",
},
{
"id": "af171c34-4ca8-4374-82bf-a418396e375c",
"label": "Additional Toppings",
},
],
},
]
}
When you say "without loops" I take it as without For Loops. because any kind of traversal of arrays, let alone nested traversal, involve iterating.
You can use the reduce method to have it done for you internally and give you the format you need.
Try this :
const data = {
sections: [
{
id: "62ee1779",
name: "Drinks",
items: [
{
id: "1902b625",
name: "Cold Brew",
optionSets: [
{
id: "45f2a845-c83b-49c2-90ae-a227dfb7c513",
label: "Choose a size"
},
{
id: "af171c34-4ca8-4374-82bf-a418396e375c",
label: "Additional Toppings"
}
]
}
]
}
]
};
x = data.sections.reduce((acc, ele) => {
acc.push(ele.name);
otherName = ele.items.reduce((acc2, elem2) => {
acc2.push(elem2.name);
label = elem2.optionSets.reduce((acc3, elem3) => {
acc3.push(elem3.label);
return acc3;
}, []);
return acc2.concat(label);
}, []);
return acc.concat(otherName);
}, []);
console.log(x);
Go ahead and press run snippet to see if this matches your desired output.
For More on info reduce method
In the context of cJSON
yes, we can fetch the key value for any of the object.
1 - each key value is pointed by one of the objects. will simply fetch that object and from there will get the key value.
In the above case for
pre-requisition: root must contain the json format and root must be the cJSON pointer. if not we can define it and use cJSON_Parse() to parse the json.
1st name object is "sections" will use
cJSON *test = cJSON_GetObjectItem(root, "sections");
char *name1 = cJSON_GetObjectItem(test, "name" )->valuestring;
2nd name key value
cJSON *test2 = cJSON_GetObjectItem(test, "items");
char *name2 = cJSON_GetObjectItem(tes2, "name")->valuestring;
likewise, we can do for others as well to fetch the key value.

Waterline.js: Populate association from list

Does anyone know if it's possible to populate a list of IDs for another model using waterline associations? I was trying to get the many-to-many association working but I don't think it applies here since one side of the relationship doesn't know about the other. Meaning, a user can be a part of many groups but groups don't know which users belong to them. For example, I'm currently working with a model with data in mongodb that looks like:
// Group
{
_id: group01,
var: 'somedata',
},
{
_id: group02,
var: 'somedata',
},
{
_id: group03,
var: 'somedata',
}
// User
{
_id: 1234,
name: 'Jim',
groups: ['group01', 'group03']
}
And I'm trying to figure out if it's possible to setup the models with an association in such a way that the following is returned when querying the user:
// Req: /api/users/1234
// Desired result
{
id: 1234,
name: 'Jim',
groups: [
{
_id: group01,
var: 'somedata',
},
{
_id: group03,
var: 'somedata',
}
]
}
Yes, associations are supported in sails 0.10.x onwards. Here is how you can setup the models
Here is how your user model will look like:
// User.js
module.exports = {
tableName: "users",
attributes: {
name: {
type: "string",
required: true
},
groups: {
collection: "group",
via: "id"
}
}
};
Here is how your group model will look like:
// Group.js
module.exports = {
tableName: "groups",
attributes: {
name: {
type: "string",
required: "true"
}
}
};
Setting up models like this will create three tables in your DB:
users,
groups and
group_id__user_group
The last table is created by waterline to save the associations. Now go on and create groups. Once groups are created, go ahead and create user.
Here is a sample POST request for creation a new user
{
"name": "user1",
"groups": ["547d84f691bff6663ad08147", "547d850c91bff6663ad08148"]
}
This will insert data into the group_id__user_group in the following manner
{
"_id" : ObjectId("547d854591bff6663ad0814a"),
"group_id" : ObjectId("547d84f691bff6663ad08147"),
"user_groups" : ObjectId("547d854591bff6663ad08149")
}
/* 1 */
{
"_id" : ObjectId("547d854591bff6663ad0814b"),
"group_id" : ObjectId("547d850c91bff6663ad08148"),
"user_groups" : ObjectId("547d854591bff6663ad08149")
}
The column user_groups is the user id. And group_id is the group id. Now if you fetch the user using GET request, your response will look like this:
{
"groups": [
{
"name": "group1",
"createdAt": "2014-12-02T09:23:02.510Z",
"updatedAt": "2014-12-02T09:23:02.510Z",
"id": "547d84f691bff6663ad08147"
},
{
"name": "group2",
"createdAt": "2014-12-02T09:23:24.851Z",
"updatedAt": "2014-12-02T09:23:24.851Z",
"id": "547d850c91bff6663ad08148"
}
],
"name": "user1",
"createdAt": "2014-12-02T09:24:21.182Z",
"updatedAt": "2014-12-02T09:24:21.188Z",
"id": "547d854591bff6663ad08149"
}
Please note that groups are not embedded in the user collection. Waterline does the fetch from groups, users and group_id__user_group to show this result to you.
Also, if you want to do this in your controller, you will need to execute like this
User.findOne({'id': "547d854591bff6663ad08149"})
.populate('groups')
.exec(function (err, user){
// handle error and results in this callback
});
Without populate('groups'), you won't get the groups array. Hope this serves your purpose

Categories

Resources