Normalising JSON data - javascript

{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
This is JSON for an article
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
Im currently looking through redux tutorials, they give a helper which normalise JSON data, does anyone know what type of normalisation this is?

Related

remove items from one object those are matched with other object items

i have an object structure is like this as below
"designProjects": [
{
"projectNumber": "number1",
"name": "test1"
},
{
"projectNumber": "number2",
"name": "test2"
},
{
"projectNumber": "number3",
"name": "test3"
},
]
i have another object that is having structure like this as below
"allProjects": [
{
"project": {
"name": "test1",
"number": "number1"
},
"employee": {
"displayName": "name1"
},
"projectRoleName": "Editor"
},
{
"project": {
"name": "test2",
"number": "number2"
},
"employee": {
"displayName": "name2"
},
"projectRoleName": "Editor"
},
]
I am kind of looking the results like as below
"designProjects": [
{
"projectNumber": "number3",
"name": "test3"
},
]
here the results is designProjects is only having one because the project number and name matched with project array of allprojects object. Is there way we can achieve this results in react js.
Any suggestions or ideas would be very grateful to me, Many thanks in advance
You would just combine .filter with .some, something like:
let d = {
"designProjects": [
{
"projectNumber": "number1",
"name": "test1"
},
{
"projectNumber": "number2",
"name": "test2"
},
{
"projectNumber": "number3",
"name": "test3"
},
]
}
let a = {
"allProjects": [
{
"project": {
"name": "test1",
"number": "number1"
},
"employee": {
"displayName": "name1"
},
"projectRoleName": "Editor"
},
{
"project": {
"name": "test2",
"number": "number2"
},
"employee": {
"displayName": "name2"
},
"projectRoleName": "Editor"
},
]
};
console.log(
d.designProjects.filter((designProject) => {
return !a.allProjects.some((project) => designProject.projectNumber === project.project.number && designProject.name === project.project.name);
})
);
You can combine filter and some
filter is used to return a new filtered array based on a condition
some will be the condition and return as soon as it finds a match
const designProjects = [{
"projectNumber": "number1",
"name": "test1"
},
{
"projectNumber": "number2",
"name": "test2"
},
{
"projectNumber": "number3",
"name": "test3"
},
];
const allProjects = [{
"project": {
"name": "test1",
"number": "number1"
},
"employee": {
"displayName": "name1"
},
"projectRoleName": "Editor"
},
{
"project": {
"name": "test2",
"number": "number2"
},
"employee": {
"displayName": "name2"
},
"projectRoleName": "Editor"
},
]
const cleaned = designProjects.filter((x) => {
return !allProjects.some(y => y.project.number === x.projectNumber);
});
console.info(cleaned);

How to get size of array embedded array mongoose?

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) {
})

how to get the value of Json?

I want to get the key and value from JSON data like below.
{
"data": {
"listCard": {
"cards": [
{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
}
i use console.log(data.listCard)
it shows below
{cards: Array(2), __typename: "ListCardResponse"}
cards: Array(2)
0: {id: "2", createdAt: "2019-04-17T16:06:31.962772+00:00", updatedAt: "2019-04-17T16:06:31.962820+00:00", title: "벗꽃볼사람", content: "하이", …}
1: {id: "1", createdAt: "2019-04-17T16:06:14.789277+00:00", updatedAt: "2019-04-17T16:06:14.789315+00:00", title: "벗꽃볼사람", content: "하이", …}
length: 2
__proto__: Array(0)
__typename: "ListCardResponse"
__proto__: Object
but i use console.log(data.listCard.cards)
it show cards is not define.
finally i want to use data.listCard.cards.map.
could you help me?
Firstly, it's not JSON - it's an ordinary JavaScript object. Secondly, using object.data.listCard.cards works perfectly:
const object = {
"data": {
"listCard": {
"cards": [{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
};
console.log(object.data.listCard.cards);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Since you wanted to use .map(). We iterate through d.data.listCard.cards. But you might want to consider using forEach.
Documentation: Map
Access the object data.listCard.cards.map or data['listCard']['cards']. Using bracket notation or dot notation.
Documentation: Property Accessors
let d = {
"data": {
"listCard": {
"cards": [
{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
}
// Map
// Or d['data']['listCard']['cards']
d.data.listCard.cards.map(v => {
console.log(v)
});
// forEach
// Or d.data['listCard']['cards']
d.data.listCard.cards.forEach(v => {
console.log(v)
});
I use map when I need to return a new array or object.
// Map Returns Array
let data = d.data.listCard.cards.map(v => v);
console.log(data);

Objects data to be updated with value from Array

I'm trying to update the 'positionTitle' field of my graphData object with the 'positionTitle fields of my individualData array.
I need to do it accurately, both sets of data have 'accounts' which both have the same id and fullname for user, I was hoping to try and use this to do the matching.
I want the positionTitle's from the users with same account id or name (whichever is easier) to go into the objects fields.
This is currently what I have:
My Object (that i want to update):
graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
}
My array whose positionTitles I want to take:
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
]
The function I'm currently using, which does take the first positiontitle field of the array:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
positionTitle: IndividualData[0].positions[0].positionTitle
}
}))
}))}))
}))
};
console.log(updatedGraphTable)
console.log('a' + JSON.stringify(updatedGraphTable))
my expected result with the positions updated:
updatedGraphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Managing Director"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Managing Director"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
My current result:
{
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
}, {
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334",
"account": {
"id": "eefe"
},
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}, {
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
}, {
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34",
"account": {
"id": "3546"
},
"position": {
"id": "3999434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546",
"account": {
"id": "3545"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
Sure, the trick would be to first map your data into an object (so you don't have to search over both arrays all the time), and then conditionally set the value (as I saw that your first manager, doesn't really have a matching position).
So to create the dictionary for usage in your later model, you can first do
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
This would then have an object where accountIdToPositionDict["123"] would be Managing Director, and then change the duplicating logic into:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
Where the position would then be set based on the found accountId in the dictionary, or the original title if no match was found
const individualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
];
const graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
};
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
// then use it in the mapping function
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
console.log( updatedGraphTable );
Try the code below.
accountPositions = {};
IndividualData.forEach((data) => {
accountPositions[data.account.id] = data.positions.filter((pos) => {return pos.isPrimary})[0].positionTitle;
});
graphData.engagementAreas.forEach((area) => {
area.engagementTypes.forEach((type) => {
type.engagements.forEach((engagement) => {
engagement.members.forEach((member) => {
if (!accountPositions[member.account.id]) return;
console.log('position updated from ', member.position.positionTitle, 'to', accountPositions[member.account.id]);
member.position.positionTitle = accountPositions[member.account.id];
});
});
});
});

JavaScript array comparison with JSON response

I have this project I'm working on and I need to get all the vacant rooms from my school's timetable where I get my data from a JSON response.
The JSON response looks like this:
{
"status": "success",
"reservations": [
{
"id": "19598",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:42",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T09:45:00",
"resources": [
{
"id": "795",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "599",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2989",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "41",
"type": "room",
"code": "A340.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A340.1"
}
],
"description": ""
},
{
"id": "27832",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:42",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T09:45:00",
"resources": [
{
"id": "52",
"type": "room",
"code": "A450.3",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A450.3"
},
{
"id": "2409",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3401",
"type": "realization",
"code": "",
"name": ""
}
],
""
},
{
"id": "10945",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:43",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T12:00:00",
"resources": [
{
"id": "289",
"type": "student_group",
"code": "groupCode",
"name": "gorupName"
},
{
"id": "2454",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "19",
"type": "room",
"code": "A510.4",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A510.4"
}
],
"description": ""
},
{
"id": "27647",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:39",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T21:00:00",
"resources": [
{
"id": "47",
"type": "room",
"code": "A420.6",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A420.6"
}
],
"description": ""
},
{
"id": "20630",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:33",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T10:45:00",
"resources": [
{
"id": "25",
"type": "room",
"code": "A130.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A130.1"
},
{
"id": "26",
"type": "room",
"code": "A130.3",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A130.3"
},
{
"id": "2997",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2268",
"type": "student_group",
"code": "groupCode",
"name": "gorupName"
}
],
"description": ""
},
{
"id": "19874",
"subject": "subjectName",
"modifiedDate": "2017-04-24T06:04:37",
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T09:45:00",
"resources": [
{
"id": "28",
"type": "room",
"code": "A140.2",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "140.2"
},
{
"id": "3033",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2338",
"type": "student_group",
"code": "groupCode",
"name": "groupname"
}
],
"description": ""
}
]
}
The response is a lot longer but I've kept it shorter for simplicity's sake.
So I've run this JSON response through with JSON.Parse() and for-loops to get all the rooms that all currently in use in an array;
var rooms = [];
for (var i = 0; i < json.reservations.length; i++) {
if(json.reservations[i].resources != null){
for(var j = 0; j < json.reservations[i].resources.length; j++){
var resource = json.reservations[i].resources[j];
if(resource.type === "room"){
if(rooms.indexOf("code"))
rooms.push(resource.code);
}
}
}
}
}
I get all the rooms that are being used at the time as you can see from the response above for example;
"startDate": "2017-04-24T08:00:00",
"endDate": "2017-04-24T09:45:00",
"type": "room",
"code": "A340.1",
But the problem is that the API that I'm using doesn't contain any data for the vacant rooms at the moment so I also made an array for all the rooms in the buildingA which looks like this:
var buildingA = ['A120.3', 'A130.1', 'A130.3', 'A140.1', 'A140.2', 'A140.4', 'A250.1', 'A240.4', 'A240.2', 'A220.5', 'A220.3',
'A220.1', 'A210.2', 'A320.2', 'A320.6', 'A320.7', 'A320.8', 'A340.1', 'A340.2', 'A350.1', 'A350.3', 'A440.5', 'A450.3',
'A450.1', 'A440.4', 'A440.2', 'A420.6', 'A420.5', 'A420.4', 'A420.2', 'A510.2', 'A520.5', 'A510.4', 'A520.6', 'A520.7',
'A540.1', 'A540.2'];
Is there any way I could compare this array to the var rooms = []; array so I could print all the vacant rooms instead of the ones being in use?
As for the results I would have to see the name of the vacant room and the time how long it stays vacant (if possible) but the main thing would be to get the room name for example;
A340.1 - 1 hour 45 minutes
A440.4 - 2 hours
Thanks in advance.
Basically, you could collect first the rooms which are booked and then get either completely free rooms or render free times.
var data = { status: "success", reservations: [{ id: "19598", subject: "subjectName", modifiedDate: "2017-04-24T06:04:42", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T09:45:00", resources: [{ id: "795", type: "student_group", code: "groupCode", name: "groupName" }, { id: "599", type: "student_group", code: "groupCode", name: "groupName" }, { id: "2989", type: "realization", code: "", name: "" }, { id: "41", type: "room", code: "A340.1", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A340.1" }], description: "" }, { id: "27832", subject: "subjectName", modifiedDate: "2017-04-24T06:04:42", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T09:45:00", resources: [{ id: "52", type: "room", code: "A450.3", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A450.3" }, { id: "2409", type: "student_group", code: "groupCode", name: "groupName" }, { id: "3401", type: "realization", code: "", name: "" }], description: "" }, { id: "10945", subject: "subjectName", modifiedDate: "2017-04-24T06:04:43", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T12:00:00", resources: [{ id: "289", type: "student_group", code: "groupCode", name: "gorupName" }, { id: "2454", type: "realization", code: "", name: "" }, { id: "19", type: "room", code: "A510.4", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A510.4" }], description: "" }, { id: "27647", subject: "subjectName", modifiedDate: "2017-04-24T06:04:39", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T21:00:00", resources: [{ id: "47", type: "room", code: "A420.6", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A420.6" }], description: "" }, { id: "20630", subject: "subjectName", modifiedDate: "2017-04-24T06:04:33", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T10:45:00", resources: [{ id: "25", type: "room", code: "A130.1", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A130.1" }, { id: "26", type: "room", code: "A130.3", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "A130.3" }, { id: "2997", type: "realization", code: "", name: "" }, { id: "2268", type: "student_group", code: "groupCode", name: "gorupName" }], description: "" }, { id: "19874", subject: "subjectName", modifiedDate: "2017-04-24T06:04:37", startDate: "2017-04-24T08:00:00", endDate: "2017-04-24T09:45:00", resources: [{ id: "28", type: "room", code: "A140.2", parent: { id: "2", type: "building", code: "A", name: "buildingA" }, name: "140.2" }, { id: "3033", type: "realization", code: "", name: "" }, { id: "2338", type: "student_group", code: "groupCode", name: "groupname" }], description: "" }] },
rooms = ['A120.3', 'A130.1', 'A130.3', 'A140.1', 'A140.2', 'A140.4', 'A250.1', 'A240.4', 'A240.2', 'A220.5', 'A220.3', 'A220.1', 'A210.2', 'A320.2', 'A320.6', 'A320.7', 'A320.8', 'A340.1', 'A340.2', 'A350.1', 'A350.3', 'A440.5', 'A450.3', 'A450.1', 'A440.4', 'A440.2', 'A420.6', 'A420.5', 'A420.4', 'A420.2', 'A510.2', 'A520.5', 'A510.4', 'A520.6', 'A520.7', 'A540.1', 'A540.2'],
booking = Object.create(null),
free;
data.reservations.forEach(function (reservation) {
reservation.resources.some(function (resource) {
if (resource.type === 'room') {
booking[resource.code] = booking[resource.code] || [];
booking[resource.code].push({ startDate: reservation.startDate, endDate: reservation.endDate });
return true;
}
});
});
free = rooms.filter(function (a) {
return !booking[a];
});
console.log(booking);
console.log(free);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hope the below helps in filtering the array.
var vacantRooms = buildingA.filter((x) => {return !rooms.find((y) => {return y == x})});

Categories