Filtering subarray of objects - javascript

I need to filter a subarray of elements.
var university = {
"fax": "123345",
"email": "test#test.com",
"url": "www.test.com",
"classes": [
{
"number": "1",
"name": "maths",
"students": [
{
"name": "Max",
"exams": [
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": false
},
{
"date": "2016-01-04T18:32:43.000Z",
"passed": true
}
]
},
{...}
]
},
{...}
]
}
Ok I need to get all the classes without filtering, all the students of each class without filtering, but in the exams array I only need to get the ones that passed.
I tried the following:
university.classes.students.exams.filter(function (el) {
return el.passed
});
But it is not working...
I've googled a solution to this without success...any help would be appreciated.

classes and students are arrays - so you have to loop those as well:
university.classes.forEach(function(uniClass) {
uniClass.students.forEach(function(student) {
student.exams = student.exams.filter(function (el) {
return el.passed;
});
});
});

Related

Getting second level nested object inside array of objects mongodb

My database looks like this:
[
{
"title": "man",
"articlesType": [
{
"title": "shoes",
"articles": [
{
"title": "shoes1",
"id": "randomId"
},
{
"title": "shoes2",
"id": "alsoRandomId"
}
]
}
]
},
{
"title": "woman",
"articlesType": [
{
"title": "pants",
"articles": [
{
"title": "pants1",
"id": "anotherRandomId"
},
{
"title": "pants1",
"id": "justId"
}
]
}
]
}
]
I expect something like this: , is it possible to get whole object in this nested just using an ID?
{
"title": "shoes2",
"id": "alsoRandomId"
}
I found this, but does not work for me
You can try an aggregation pipeline using double $unwind to deconstruct the array twice and then filter by your desired id (I'm assuming you want to match by the id).
And the last step, $project is to output the result in the same way as you want.
db.collection.aggregate([
{
"$unwind": "$articlesType"
},
{
"$unwind": "$articlesType.articles"
},
{
"$match": {
"articlesType.articles.id": "alsoRandomId"
}
},
{
"$project": {
"title": "$articlesType.articles.title",
"id": "$articlesType.articles.id"
}
}
])
Example here

addToSet mongoDB not adding if one value is repeated

I have the following collection in MongoDB
[
{
"acronym": "front",
"references": [
{
"date": "2020-03-04",
"value": "5.6"
},
{
"date": "2020-03-05",
"value": "6.3"
}
]
}
]
I want to use the function $addToSet in order to add new document into references. I know that it can be done with the following code:
db.collection.update({
"acronym": "front"
},
{
$addToSet: {
"references": {
"date": "2020-03-06",
"value": "6"
}
}
})
And it will add the new document to the array references, so the result is the following:
[
{
"acronym": "front",
"references": [
{
"date": "2020-03-04",
"value": "5.6"
},
{
"date": "2020-03-05",
"value": "6.3"
},
{
"date": "2020-03-06",
"value": "6"
}
]
}
]
QUESTION: What I want to obtain is that in the case of adding a date that is already in the array, the update will no be produced.
Here is the playground: https://mongoplayground.net/p/DPER2RuROEs
Thanks!
You can add another qualifier to the update to prevent duplicated dates
db.collection.update({
"acronym": "front",
"references.date": {
$ne: "2020-03-04"
}
},
{
$addToSet: {
"references": {
"date": "2020-03-04",
"value": "6"
}
}
})
I got the solution from here

javascript map object multidimension

i have this data structure:
tree = [
{
"name": "Men Section",
"categories": [
{
"name": "Clothings",
"Subcategories": [
{
"name": "Jackets",
"products": [
{
"name": "jacket 01",
"price": 100
},
{
"name": "jacket 02",
"price": 140
},
// ..and so on
]
]
},
// ..and so on
]
} // ..and so on
]
how can i add new property in products item isSelected: false in javascript (ES5 or ES6 is fine) so the object will be
{
"name": "jacket 01",
"price": 100,
"isSelected": false
}
?
It could be useful, it works for me
tree.forEach(base => {
base.categories.forEach(categories => {
categories.Subcategories.forEach(subCategory =>{
subCategory.products.forEach(product => product.isSelected = false)
})
});
});
so yeah, i should traverse deep to the object with nested foreach. i came up with this:
tree.categories.forEach(function (category) {
category.subcategories.forEach(function (subcategory) {
subcategory.products.forEach(function (product) {
product.isSelected = false;
})
})
})
thanks for the enlightment

JSON group by key value to new JSON Javascript

I have been reading some posts which are related to my question, whereas I have not been able to find a proper solution for what I'm trying to do hear.
I have this JSON file that I am obtaining directly from my database via a sql query:
[
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-21",
"price": 14.173041264216105
}
]
},
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
}
]
My objectif is to be able to sort/transform this json object to a new json object which is classified by the scenario, so, something that looks like:
[
{
"scenario": "scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18",
"data": [
{
"date": "2018-05-21",
"price": 14.173041264216105
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
},
{
"scenario": "scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99",
"data": [
{
"date": "2018-05-22",
"price": 42.94691197077433
},
{
"date": "2018-05-22",
"price": 42.94691197077433
}
]
I have been trying some javascript selfmade functions but I have not obtainend the desired result.
This is the last thing I've tried:
let estructura = [];
for (var j =0; j<obj.length; j++){
for (var i=0; i<estructura.length; i++){
if(obj[j]['scenario'] == estructura[i]['scenario']){
estructura[i]['data'].push(obj[j]['data'])
} else {
console.log("no match, we add the scenario to estructura")
estructura.push(
{
scenario:obj[j]['scenario'],
data: []
})
}
}
}
Thank you
You can achieve this easily with built-in functions like reduce. Iterate over the input, grouping into an object indexed by scenario, creating a object with a data array if the scenario doesn't exist yet, and push to that array:
const input=[{"scenario":"scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18","data":[{"date":"2018-05-21","price":14.173041264216105}]},{"scenario":"scenario-483d742c-4492-4a4f-95fa-7ccceac8bb18","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-c705069f-fa53-4ff3-9f07-3fcbf9dc8d15","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99","data":[{"date":"2018-05-22","price":42.94691197077433}]},{"scenario":"scenario-d58bb001-d7ed-4744-8f6c-8377519c7a99","data":[{"date":"2018-05-22","price":42.94691197077433}]}]
console.log(
Object.values(input.reduce((a, { scenario, data }) => {
if (!a[scenario]) a[scenario] = { scenario, data: [] };
a[scenario].data.push(data[0]);
return a;
}, {}))
);

Add key values dynamically to nested object in Javascript

This might be a duplicate of this but did not get proper solution over there. I have object as below,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
]
}
}
}
}
}
I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,
"cc": {
"address": [
ccEmailId
]
}
So it will look like,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
],
"cc": {
"address": [
ccEmailId
]
}
}
}
}
}
}
I tried to add this using object[key] as below, object.key but no luck
replyDataObj[payload][emailAddresses][cc]={
"address": [
ccEmailId
]
}
I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.
Put strings inside []:
replyDataObj['payload']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}
As answered by #K.Kirsz, I was missing strings inside [] (quotes). Also added missing 'email' key to solve my issue.
replyDataObj['payload']['email']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}

Categories