I have two arrays, one for categories and other for products. Products contain multiple categories as a comma-separated string. Now I want to match a particular category and add the matched product to an array to each category.
I want to match the category to product_category.
Here are the arrays
Products
[
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
]
Categories
[
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
}
]
Code that I try but not working
this.categories.forEach(cat => {
this.products.filter(prod => {
if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
this.categories.push(prod);
}
});
});
Please help me to solve this issue.
Any solution appreciated!
You could use .map() on categories to add a products property to it. This property will be the result of a .filter() on the products.
const categoriesWithProducts = categories.map(cat => {
return {
...cat,
products: products.filter(prod => {
return prod.product_category.split(',').includes(cat.category_name);
})
};
});
``
One of the approaches is to create a new array where you would push products mapped to specific categories:
var products = [
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
];
var categories = [
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
}
]
var productCategories = [];
categories.forEach((cat)=> {
var productCategory = {};
productCategory.category = cat;
productCategory.products = [];
products.forEach(prod => {
if (prod.product_category.indexOf(cat.category_name) !== -1) {
productCategory.products.push(prod);
}
});
productCategories.push(productCategory);
console.log(productCategories);
});
You do not need filter(), you can use another forEach() with includes() and Object.assign():
var products = [
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
];
var categories = [
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
}
]
categories.forEach((cat,i) => {
products.forEach(prod => {
if (prod.product_category.split(',').includes(cat.category_name)) {
Object.assign(categories[i], prod);
}
});
});
console.log(categories);
You can use Array#filter to filter products on catagory names using Array#some
let products = [{"id":1,"product_title":"Product 1","product_size":null,"product_author":5,"description":"Test Description","product_category":"Shirts,Pents,Salwar","createdAt":"2020-02-08T11:42:15.000Z","updatedAt":"2020-02-08T11:42:15.000Z"},{"id":4,"product_title":"Product 2","product_size":null,"product_author":5,"description":"Test Description","product_category":"Pents,Salwar","createdAt":"2020-02-08T11:42:15.000Z","updatedAt":"2020-02-10T07:08:23.000Z"}]
let catagories = [{"id":1,"category_name":"Shirts","createdAt":"2020-02-08T04:59:59.000Z","updatedAt":"2020-02-10T06:50:05.000Z"},{"id":9,"category_name":"Pents","createdAt":"2020-02-08T04:59:59.000Z","updatedAt":"2020-02-10T06:50:05.000Z"}]
let catagoryNames = new Set(catagories.map(e => e.category_name));
let filtered = [...products].filter(e => e.product_category.split(',').some(cat => catagoryNames.has(cat)));
console.log(filtered)
Try this
categories.forEach(function(c){
c.products=products.filter(function(p){
var reg=new RegExp(c.category_name,'gi');
return reg.test(p.product_category)
})
})
Without Regex
categories.forEach(function(c){
c.products=products.filter(function(p){
return (p.product_category.split(',').indexOf(c.category_name)!==-1)
})
})
You will get the products inside each category
Fiddle here
Try this code.I hope it will helps you.
product = [
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
]
categories=[
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z",
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z",
}
]
this.categories.forEach(cat => {
cat['product'] = []
this.product.filter(prod => {
if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
cat['product'].push(prod);
}
});
});
console.log(this.categories)
You can easily loop through all categories and then loop throgh all products. For each product check if category name is present and if so add product to category products:
this.categories.forEach(cat => {
cat.products = [];
this.products.forEach(prod => {
if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
cat.products.push(prod);
}
});
});
Please note that I changed filter to forEach.
const products = [
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
];
const categories = [
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
}
];
const matchedProducts = [];
products.map(prod=>{
const isCateoryMatched = categories.some(c=>{
return prod.product_category.includes(c.category_name)
});
if(isCateoryMatched ){
matchedProducts.push(prod);
}
})
//if you want to push the matched products into categories
categories.push(...matchedProducts)
console.log('matchedProducts',matchedProducts);
console.log('categories',categories);
Related
So I have the following JSON array
[
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
},
{
"URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID": 853,
"description": "Picture 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "IMAGE",
"userID": 1
},
{
"URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID": 1,
"description": "Gif 1",
"id": 1,
"seriesID": 1,
"status": "ACCEPTED",
"type": "GIF",
"userID": 1
},
{
"characterID": 0,
"description": "Idea 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "IDEA",
"userID": 1
}
]
However I want to achieve splitting the arrays as follows
[
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
}
]
[
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
}
]
What I want to achieve is split the JSON in segments based on what type it contains within the array.
I am working in Javascript / Vue, if there's any solutions for this, would be appreciated.
Array.reduce, will work nicely here.
Below is an example.
var data = JSON.parse('[{"characterID":0,"description":"Series 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Series 2","id":2,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Character 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"CHARACTER","userID":1},{"URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg","characterID":853,"description":"Picture 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"IMAGE","userID":1},{"URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif","characterID":1,"description":"Gif 1","id":1,"seriesID":1,"status":"ACCEPTED","type":"GIF","userID":1},{"characterID":0,"description":"Idea 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"IDEA","userID":1}]');
const grouped = data.reduce((a, v) => {
if (!a[v.type]) a[v.type] = [];
a[v.type].push(v);
return a;
}, {});
console.log(grouped);
You can use reduce to create a new object with type as keys:
var res = data.reduce((acc, val) => {
if (!acc[val.type]) {
acc[val.type] = [val];
} else {
acc[val.type].push(val)
}
return acc;
}, {})
The result will look something like:
{
"SERIES":[
{
"characterID":0,
"description":"Series 1",
"id":1,
"seriesID":0,
"status":"ACCEPTED",
"type":"SERIES",
"userID":1
},
{
"characterID":0,
"description":"Series 2",
"id":2,
"seriesID":0,
"status":"ACCEPTED",
"type":"SERIES",
"userID":1
}
],
"CHARACTER":[
{
"characterID":0,
"description":"Character 1",
"id":1,
"seriesID":25,
"status":"ACCEPTED",
"type":"CHARACTER",
"userID":1
}
],
"IMAGE":[
{
"URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID":853,
"description":"Picture 1",
"id":1,
"seriesID":25,
"status":"ACCEPTED",
"type":"IMAGE",
"userID":1
}
],
"GIF":[
{
"URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID":1,
"description":"Gif 1",
"id":1,
"seriesID":1,
"status":"ACCEPTED",
"type":"GIF",
"userID":1
}
],
"IDEA":[
{
"characterID":0,
"description":"Idea 1",
"id":1,
"seriesID":0,
"status":"ACCEPTED",
"type":"IDEA",
"userID":1
}
]
}
I am not sure if you want to split and store into separate arrays or not but, if thats the case you can try this:
const obj = [
{
"characterID": 0,
"description": "Series 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Series 2",
"id": 2,
"seriesID": 0,
"status": "ACCEPTED",
"type": "SERIES",
"userID": 1
},
{
"characterID": 0,
"description": "Character 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "CHARACTER",
"userID": 1
},
{
"URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
"characterID": 853,
"description": "Picture 1",
"id": 1,
"seriesID": 25,
"status": "ACCEPTED",
"type": "IMAGE",
"userID": 1
},
{
"URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
"characterID": 1,
"description": "Gif 1",
"id": 1,
"seriesID": 1,
"status": "ACCEPTED",
"type": "GIF",
"userID": 1
},
{
"characterID": 0,
"description": "Idea 1",
"id": 1,
"seriesID": 0,
"status": "ACCEPTED",
"type": "IDEA",
"userID": 1
}
];
const seriesTypeObjs = [];
obj.map(eachObj => {
if (eachObj.type === 'SERIES'){
seriesTypeObjs.push(eachObj);
}
});
console.log('Series Type Objs =>', seriesTypeObjs);
You can use the same code to test for other type values too.
The easiest way is using a utility library like lodash
Specifically method groupBy
_.groupBy(data, 'type');// {SERIES: Array(2), CHARACTER: Array(1), IMAGE: Array(1), GIF: Array(1), IDEA: Array(1)}
UPDATE:(vanilla approach without any libraries)
Solution Using The Map which is object holds key-value pairs key is the type and value is their entry group of that type with ?. Optional chaining and ?? Nullish coalescing operator
let map = new Map()
for(entry of data){
const type = entry?.type ?? "untyped";
map.set(type, [...map.get(type)??[],entry])
}
// Map(5) {'SERIES' => Array(2), 'CHARACTER' => Array(1), 'IMAGE' => Array(1), 'GIF' => Array(1), 'IDEA' => Array(1)}
I have a mongodb data response like the output below and want to group the results of the array field studentsTakingSubject by the dateStarted and then a count of studentId in the corresponding month but all my efforts have not worked. Please I need help
{
"data": {
"getSubjectPerformanceAnalysis": [
{
"_id": "5f11d2f4a40eff3f6af5ac31",
"teacherAssigned": "5ecfb15a6b60d08d688fd519",
"subjectName": "English",
"term": "third",
"classId": "5ef9fbcbcd7361513a423393",
"code": "Sub-686c0d",
"createdAt": "2020-07-17T16:33:56.029Z",
"updatedAt": "2020-07-31T14:35:25.574Z",
"__v": 0,
"studentsTakingSubject": [
{
"_id": "5f2424c7da6c6c344362d633",
"studentId": "5f1583c488fbd82308e86e37",
"dateStarted": "2020-07-31T13:53:26.000Z",
"updatedAt": "2020-07-31T14:03:51.590Z",
"createdAt": "2020-07-31T14:03:51.590Z"
},
{
"_id": "5f242570da6c6c344362d636",
"studentId": "5f11d1d0a40eff3f6af5ac2e",
"dateStarted": "2020-07-31T13:53:26.000Z",
"updatedAt": "2020-07-31T14:06:40.298Z",
"createdAt": "2020-07-31T14:06:40.298Z"
},
{
"_id": "5f2426ffda6c6c344362d63d",
"studentId": "5f199749aa89b14929b68c39",
"dateStarted": "2020-06-19T13:53:26.000Z",
"updatedAt": "2020-07-31T14:13:19.580Z",
"createdAt": "2020-07-31T14:13:19.580Z"
},
{
"_id": "5f242c2df97301390dc90b3e",
"studentId": "5f199749aa89b14929b68c39",
"dateStarted": "2020-06-19T13:53:26.000Z",
"updatedAt": "2020-07-31T14:35:25.574Z",
"createdAt": "2020-07-31T14:35:25.574Z"
}
]
}
]
}
}
I need an output like this
[
{
"_id": "01",
"count": 1
},
{
"_id": "02",
"count": 5
},
{
"_id": "03",
"count": 7
},
{
"_id": "04",
"count": 20
}
]
```
I'm trying to compare two JSONs files in NodeJs.
If there is a review that matches the place id, I need to push the review data into the places JSON. If there are no matching reviews, it pushes an empty array.
Here is the code:
//places JSON
[{
"id": 1,
"title": "Hotel in Sidney",
"maxNumberOfGuests": 5,
"description": "Quiet place by the water.",
"createdAt": "2019/12/7 14:34",
"price": 120
},
{
"id": 2,
"title": "Cabin in Italy",
"maxNumberOfGuests": 2,
"description": "Romantic lake cabin for two.",
"createdAt": "2019/4/7 10:00",
"price": 250
}
]
//reviews JSON
[{
"id": 1,
"numberOfStars": 3,
"content": "Comfy place",
"placeId": 1,
"createdAt": 12345
},
{
"id": 2,
"numberOfStars": 4,
"content": "Awesome lake view.",
"placeId": "",
"createdAt": 23456
}
]
Here is the desired result:
[{
"id": 1,
"title": "Hotel in Sidney",
"maxNumberOfGuests": 5,
"description": "Quiet place by the water.",
"createdAt": "2019/12/7 14:34",
"reviews": [{
"id": 1,
"numberOfStars": 3,
"content": "Comfy place",
"placeId": 1,
"createdAt": 12345
}],
"price": 120
},
{
"id": 2,
"title": "Cabin in Italy",
"maxNumberOfGuests": 2,
"description": "Romantic lake cabin for two.",
"createdAt": "2019/4/7 10:00",
"reviews": [],
"price": 250
}
]
this is how far I could get:
places.forEach(p => {
const { id } = p;
console.log(id);
return id;
});
reviews.forEach(r => {
const { id, numberOfStars, content, placeId, createdAt } = r;
// console.log(id, numberOfStars, content, placeId, createdAt);
console.log(r);
return r;
});
//node express routes to places where will display the desired result.
router.get('/places', function(req, res) {
res.json(places);
});
I just can't make it work and need some help.
Thanks in advance.
try this
let places =[{
"id": 1,
"title": "Hotel in Sidney",
"maxNumberOfGuests": 5,
"description": "Quiet place by the water.",
"createdAt": "2019/12/7 14:34",
"price": 120
},
{
"id": 2,
"title": "Cabin in Italy",
"maxNumberOfGuests": 2,
"description": "Romantic lake cabin for two.",
"createdAt": "2019/4/7 10:00",
"price": 250
}
];
let reviews =[{
"id": 1,
"numberOfStars": 3,
"content": "Comfy place",
"placeId": 1,
"createdAt": 12345
},
{
"id": 2,
"numberOfStars": 4,
"content": "Awesome lake view.",
"placeId": "",
"createdAt": 23456
}
];
places.forEach(function(place) {
place.reviews = reviews.filter(review => review.placeId ===place.id);
});
console.log(places);
I would first reduce the reviews array into an object keyed by placeId.
const reviews = [{
"id": 1,
"numberOfStars": 3,
"content": "Comfy place",
"placeId": 1,
"createdAt": 12345
},
{
"id": 2,
"numberOfStars": 4,
"content": "Awesome lake view.",
"placeId": "",
"createdAt": 23456
}
];
const reviewsHashmap = reviews.reduce((acc, review) => {
if (!review.placeId) return acc;
acc[review.placeId] = acc[review.placeId] || [];
acc[review.placeId].push(review);
return acc;
}, {})
This makes it more performant when adding the reviews property, because now you do not need to filter the reviews array again and again for each place.
const places = [
{
"id": 1,
"title": "Hotel in Sidney",
"maxNumberOfGuests": 5,
"description": "Quiet place by the water.",
"createdAt": "2019/12/7 14:34",
"price": 120
},
{
"id": 2,
"title": "Cabin in Italy",
"maxNumberOfGuests": 2,
"description": "Romantic lake cabin for two.",
"createdAt": "2019/4/7 10:00",
"price": 250
}
];
const placesWithReviews = places.map(place => ({
...place,
reviews: reviewsHashmap[place.id] || []
}))
Now you should have the original places array, but with each place an additional reviews property.
I have a category collection and I want to get category by id with some options. This is collection's structure in database.
[
{
"_id": "5d67296bf35b984e74486924",
"name": "Dinrk",
"images": [],
"recipes": [
{
"name": "Coffee",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"components": [
{
"name": "Dink 1",
"quantity": "1"
},
{
"name": "Dink 2",
"quantity": "1"
},
{
"name": "Dink 2",
"quantity": "1"
}
],
"cook_steps": [
{
"des": "This is description",
"pictures": []
},
{
"des": "This is description",
"pictures": []
}
]
},
{
"name": "Coffee",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"components": [
{
"name": "Dink 1",
"quantity": "1"
},
{
"name": "Dink 2",
"quantity": "1"
}
],
"cook_steps": [
{
"des": "This is description",
"pictures": []
},
{
"des": "This is description",
"pictures": []
}
]
}
]
},
{
"_id": "5d67296bf35b984e74486435555",
"name": "Cake",
"images": [],
"recipes": [
{
"name": "Cake",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"components": [
{
"name": "Cake 1",
"quantity": "1"
},
{
"name": "Cake 2",
"quantity": "1"
},
{
"name": "Cake 2",
"quantity": "1"
}
],
"cook_steps": [
{
"des": "This is description",
"pictures": []
},
{
"des": "This is description",
"pictures": []
}
]
},
{
"name": "Coffee",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"components": [
{
"name": "Cake 1",
"quantity": "1"
}
],
"cook_steps": [
{
"des": "This is description",
"pictures": []
},
{
"des": "This is description",
"pictures": []
}
]
}
]
}
]
This is my code to try categoryId = "5d67296bf35b984e74486924"
Category.aggregate([
{
$match: {'_id': categoryId}
},
{
$unwind: '$recipes'
},
{
$project: {
'total_components': {'$size': '$recipes.components'},
'total_cook_steps': {'$size': '$recipes.cook_steps'}
}
}
]).then(function(data) {
}, function(err) {
})
And expected result is
{
"_id": "5d67296bf35b984e74486924",
"name": "Dinrk",
"images": [],
"recipes": [
{
"name": "Coffee",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"total_components": 3,
"total_cook_steps": 2
},
{
"name": "Coffee",
"time": 20,
"img": "https://google.com/image-example.jpg",
"des": "This is description",
"serving": 2,
"total_components": 2,
"total_cook_steps": 2
}
]
}
But when I run above my code, result is [].
If you understand my problem, please help me. I have search a lot, but not found solution. So I want to ask everyone. Thankyou so much.
Your query is not giving you the desired result since Mongoose does not auto-cast the 24 char hex string to ObjectId in its aggregate pipeline since $project and $group can change the schema in surprising ways that it becomes hard to infer what should be an ObjectId.
You need to manually convert the categoryId
string to ObjectId using the mongoose.Types.ObjectId method.
Compute the new fields within a $map operator instead of $unwind as this allows you an aggregate operation with fewer pipeline steps
Category.aggregate([
{ '$match': { '_id': mongoose.Types.ObjectId(categoryId) } },
{ '$addFields': {
'recipes': {
'$map': {
'input': '$recipes',
'in': {
'name': '$$this.name',
'time': '$$this.time',
'img': '$$this.img',
'des': '$$this.des',
'serving': '$$this.serving',
'total_components': { '$size': '$$this.components' },
'total_cook_steps': { '$size': '$$this.cook_steps' }
}
}
}
} }
]).then(function(data) {
}, function(err) {
})
I want to delete and rename some props of my existing JSON Object to use it with select2/select2 query plugins
My JSON object that i need to transform is:
[
{
"id": 1,
"type": "Subject1",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 1,
"name": "sub1",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 1
}
]
},
{
"id": 2,
"type": "Subject2",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 16,
"name": "sub2",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 2
}
]
},
{
"id": 3,
"type": "Subject3",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 22,
"name": "sub3",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 3
}
]
}
]
To
[
{
"text": "Subject1",
"children": [
{
"id": 1,
"text": "sub1"
}
]
},
{
"text": "Subject2",
"children": [
{
"id": 16,
"text": "sub2"
}
]
},
{
"text": "Subject3",
"children": [
{
"id": 22,
"text": "sub3"
}
]
}
]
I need to :
rename name and type to text
delete tagType, updatedAt and createdAt
rename Tags to children
remove the id of each top objects
Is there a way to do all this using lodash ?
What the best way?
var res = _.map(items, function(item){
return {
text: item.type,
children: _.map(item.Tags, function(tag){
return {
id: tag.id,
text: tag.name
};
})
};
});
I succed using this link by nesting two return :
Creating new javascript Object form existing one
var result = tags.map(function(obj) {
return {
text: obj.type,
childrens:obj.Tags.map(function(obj) {
return {
id : obj.id,
text : obj.name
}
})
};
});