I am trying to create a nested JSON object using NodeJS. I am getting data from the JIRA software server and trying to map to my application's schema. Below is my application's schema.
schema:
Product:
_id: ObjectId
categories: [Category]
backlog: [Section]
Category:
_id: ObjectId
name: String
color: String
Section:
_id: ObjectId
title: String
backlogItems: [BacklogItem]
BacklogItem:
_id: ObjectId
productId: ObjectId
title: String
description: String
category: Category
acceptanceCriteria: [AcceptanceCriterion]
tasks: [Task]
notes: [Note]
I want to create one category for tasks. For example, if there are two or more issues from JIRA of type "Epic", I want to create only one category and then I want to create an array of BacklogItems but it is giving me below error:
categories: [Category], Category is not defined
Below is what I am trying to do:
function parseResponse(body) {
var data = JSON.parse(body);
result.product = {
id: ObjectID(),
categories: [Category],
backlog: [Section]
};
for (var i = 0; i < data.issues.length; i++) {
var color;
var categoryName;
switch (data.issues[i].fields.issuetype.name) {
case "Story":
color = "green";
break;
case "Epic":
color = "purple";
break;
case "Task":
color = "blue";
break;
case "Bug":
color = "red";
break;
}
var uniqeCategory = [
...new Set(data.issues.map(x => x.fields.issuetype.name))
];
if (uniqeCategory[i] !== data.issues[i].fields.issuetype.name) {
categoryName = uniqeCategory[i];
} else {
categoryName = data.issues[i].fields.issuetype.name;
}
console.log(uniqeCategory);
result.product.backlog.push({
id: ObjectID(),
title: "importer",
backlogItem: []
});
result.product.backlog.backlogItem.push({
id: data.total,
productId: result.product.id,
title: data.issues[i].fields.summary,
description: data.issues[i].fields.description,
category: data.issues[i].fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: []
});
Can somebody try to tell me what I am doing wrong and How can I create such an object?
PS: I just started working with NodeJS and trying to learn it by doing it.
After some efforts, I tried to create an object. Below is my code.
for (var j = 0; j < issue.fields.attachment.length; j++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.attachment[j].created,
content: issue.fields.attachment[j].filename,
attachmentUrl: issue.fields.attachment[j].content,
attachmentPreviewUrl: issue.fields.attachment[j].thumbnail
};
notesArray.push(note);
}
/* Creating seaparate notes by taking comments from each JIRA issue and put it in form of note */
for (var k = 0; k < issue.fields.comment.comments.length; k++) {
var note = {
_id: ObjectID(),
createdAt: issue.fields.comment.comments[k].created,
content: issue.fields.comment.comments[k].body,
attachmentUrl: "",
attachmentPreviewUrl: ""
};
notesArray.push(note);
}
/* Creating backlog items */
result.product.backlog.push({
_id: ObjectID(),
productId: result.product._id,
title: issue.fields.summary,
description: issue.fields.description,
category: issue.fields.issuetype.name,
acceptanceCriteria: [],
tasks: [],
notes: notesArray
});
console.log("final", result.product);
});
Related
I have a requirement where the array of objects needs to be sorted on certain keys. The keys with which it needs to be sorted is dynamic and it is Not fixed.
I came across array-sort in npm library. Using that, am able to sort on multiple keys but it sorts only on ascending order.
const input = [{id:'1',name:'John',city:'Denver',State:'CO'},
{id:'2',name:'Smith',city:'San Fransisco',State:'CA'},
{id:'3',name:'Adam',city:'Concord',State:'CA'},
{id:'1',name:'John',city:'Concord',State:'CA'}]
I want to sort on State (asc), city (asc) and id (desc). My output should look like
[
{id:'3',name:'Adam',city:'Concord',State:'CA'},
{id:'1',name:'John',city:'Concord',State:'CA'},
{id:'2',name:'Smith',city:'San Fransisco',State:'CA'},
{id:'1',name:'John',city:'Denver',State:'CO'}]
Can anyone please let me know how i can implement sorting on descending using array-sort
Thanks
Maybe you want a JavaScript function like this?
function multicolumnSort(data, orders) {
return data.sort((e1, e2) => {
for (var i = 0; i < orders.length; i++)
if (e1[orders[i].column] != e2[orders[i].column])
return orders[i].desc ^ e2[orders[i].column] < e1[orders[i].column]? 1 : -1;
return 0;
});
}
Then, you may call the function with your order keys:
let orders = [
{
column: 'State'
},
{
column: 'city'
},
{
column: 'id',
desc: true
}
];
let result = multicolumnSort(input, orders);
Check my code
function DESC(i, ii) { // DESC
return (i[key] > ii[key]) ? -1 : ((i[key] < ii[key]) ? 1 : 0);
}
function ASC(i, ii) { // ASC
return (i[key] > ii[key]) ? 1 : ((i[key] < ii[key]) ? -1 : 0);
}
function StartSort(data, myArray, order) {
// data - row for sorting, array - array fo sorting, order - order of sorting
key = data;
arr = myArray;
if (order.toUpperCase() == "ASC") {
sortedArray = arr.sort(ASC);
} else {
sortedArray = arr.sort(DESC);
}
return sortedArray;
}
//sorting started
const input = [{
id: '1',
name: 'John',
city: 'Denver',
State: 'CO'
},
{
id: '2',
name: 'Smith',
city: 'San Fransisco',
State: 'CA'
},
{
id: '3',
name: 'Adam',
city: 'Concord',
State: 'CA'
},
{
id: '1',
name: 'John',
city: 'Concord',
State: 'CA'
}
]
let output1 = StartSort('state', input, 'ASC');
output1 = StartSort('city', output1, 'ASC');
output1 = StartSort('id', output1, 'DESC');
console.log(output1);
Anyone can give me any suggestions ? I am trying to add an item in every 2 content. I couldn't see anything wrong with the code but why is the MyAds number repeating in all my ads entries ? it is supposed to start from MyAds0 and adding on.
MyAds2
Content1
Content2
MyAds2
Content3
Content4
MyAds2
Content5
Here is my code
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
]
let TheData = InsertContent();
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = [ {name:'tmp', subtitle:'tmp'}];
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData[0].name = 'MyAds' + adscounter;
tmpData[0].subtitle = 'My MyAds Sub' + adscounter;
thisdata = [...thisdata, tmpData[0]];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
Actually the Problem is not with the logic but with the way you are using object and array with spread operator. You really don't have to use a object at first index in a array Instead you can directly use the object with spread operator to store into the array. I just modified your code to make it work as per your requirements.
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
];
let TheData = InsertContent();
console.log(TheData);
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = {name:'', subtitle:''};
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData = {
name: 'MyAds' + adscounter,
subtitle : 'My MyAds Sub' + adscounter
};
thisdata = [...thisdata, tmpData];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
So I have a problem with my var array to add a new chapter, how would I go about this would I have to do this:
array.push({
chapter: [
{
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
}
]
});
RiTest.ts
import * as mongoose from 'mongoose';
const Scheme = mongoose.Schema;
export const RiTestScheme = new Scheme({
novelName: String,
novelAuthor: String,
novelCoverArt: String,
novelTags: Array,
chapters: [
{
id: Number,
title: String,
content: String,
authorNotes: String
}
]
});
export class RiTestController {
public addChapter(callback: (data) => void) {
var chapterInfoModel = mongoose.model('ChaptersTest', RiTestScheme);
var array = [
{
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
}
];
let newChapterInfo = new chapterInfoModel(array);
newChapterInfo.save((err, book) => {
if (err) {
return callback(err);
} else if (!err) {
return callback(book);
}
});
}
}
This doesn't work, var array doesn't get saved into let newChapterInfo = new chapterInfoModel(array); what I am trying to do add another chapter to array.chapter but the array doesn't get recognized in the chapterInfoModel() how would I fix this array and add an item to the array to create a new entry into this existing collection
thank for taking your time to answer my question.
You are trying to insert array of document to your collections, That the reason its not inserting into your collection.
Document.prototype.save() will insert only one document to your collection depends on your definition. So to insert chapter here is the code below,
//array as Object
var array = {
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
};
//Push to your chapter array
array.chapter.push({
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
});
let newChapterInfo = new chapterInfoModel(array);
Data
countries: [
{
id: 'qwe123rty456',
name: 'Australia',
regions: [
{
id: 'poi098uyt765',
name: 'Western Australia'
},
{
id: '123poi098qwe',
name: 'Queensland'
}
]
}
]
I can get a specific country with the following:
$scope.country = $meteor.object(Countries, $stateParams.countryId);
But how can I get a specific region instead? Such as:
{id: '123poi098qwe', name: 'Queensland'}
It seems that $meteor.object accepts only MongoDB objects as a first parameter. You may try to loop your result to find the inner regions as:
$scope.country = $meteor.object(Countries, $stateParams.countryId);
$scope.objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
$scope.region = $scope.objectFindByKey($scope.country["regions"], "id", "your_id");
Or try to fetch your MongoDb collection using Meteor's core driver
I've an array that contains assignments of employees on tasks, it looks like something like this:
$scope.assignments = [
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Kill everyone", project:"Destruction"
},
date: {
day:"01/01", year:"1985"
}
},
{
employee: {
id:"2", firstname:"Luke", lastname:"Skywalker"
},
task: {
name:"Find daddy", project:"Star Wars"
},
date: {
day:"65/45", year:"1000000"
}
},
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Save the world", project:"Destruction"
},
date: {
day:"02/01", year:"1985"
}
}
];
I would like to group by employee, for having something like this:
$scope.assignmentsByEmployee = [
{ //First item
id:"1",
firstname:"John",
lastname:"Rambo",
missions: [
{
name:"Kill everyone",
date:"01/01",
year:"1985"
},
{
name:"Save the world",
date:"02/01",
year:"1985"
}
]
},
{ //Second item
id="2",
firstname:"Luke",
lastname:"Skywalker",
missions: [
name:"Find daddy",
date:"65/45",
year:"1000000"
]
}
];
Is their a simple way to do this ? I tried something with a double forEach, but it leads me nowhere.
Hope I'm understandable :)
Thanks !
You should just be able to loop through the assignments array and create a 'keyed array' (which just means using an object in JavaScript) on employee ID. Then you just fill up the missions array as required.
Something like
// initialise a holding object
var assignmentsByEmployee = {};
// loop through all assignemnts
for(var i = 0; i < $scope.assignments.length; i++) {
// grab current assignment
var currentAssignment = $scope.assignments[i];
// grab current id
var currentId = currentAssignment.employee.id;
// check if we have seen this employee before
if(assignmentsByEmployee[currentId] === undefined) {
// we haven't, so add a new object to the array
assignmentsByEmployee[currentId] = {
id: currentId,
firstname: currentAssignment.employee.firstname,
lastname: currentAssignment.employee.lastname,
missions: []
};
}
// we know the employee exists at this point, so simply add the mission details
assignmentsByEmployee[currentId].missions.push({
name: currentAssignment.task.name,
date: currentAssignment.date.day,
year: currentAssignment.date.year
});
}
These leaves assignmentsByEmployee as an object, but you can simply foreach through it and convert it back to an array if required. E.g:
$scope.assignmentsByEmployee = [];
for(var employeeId in assignmentsByEmployee) {
$scope.assignmentsByEmployee.push(assignmentsByEmployee[employeeId]);
}