map key value pairs while export excel sheet using alasql - angularjs

I am working on export into excel sheet requirement using 'alasql'.
My Javasript object to be given as input to alasql is
0:
ContactEmail: "email1#example.com"
ContactName: "abcd"
CustomerName: "defg"
SubdomainName: "adasdasd"
1:
ContactEmail: "email2#example.com"
ContactName: "abcd"
CustomerName: "defg"
SubdomainName: "adasdasd"
2:
ContactEmail: "email3#example.com"
ContactName: "abcd"
CustomerName: "defg"
SubdomainName: "adasdasd"
below is my alasql script to export into excel sheet
var sheet_name = 'clients.xlsx'
alasql('SELECT * INTO XLSX("'+sheet_name+'",{headers:true}) FROM ?', arrayToExport);
My probem here is, it is exporting only the first key that is '0' & '1' key values and headers like below:
0 1
CustomerName name1
ContactName contact1
ContactEmail email1#example.com
SubdomainName adasdasd
JS Includes:
<script src="{{ asset(auto_version('public/js/alasql.min.js')) }}"></script>
<script src="{{ asset(auto_version('public/js/alasql_xlsx.js')) }}"></script>
Can anyone please assist me in this. Thanks.

I have fixed this issue. I hope this may be helpful for others. I have fixed it as first I have tried by giving directly a javascript object which is not the right way so, I have converted the javascript object to array and then object, also the array should be in a key:value pair for each array-object iteration. I think you may be confused little bit but after watching it you will get clarity. My array-object is like below:
arrayToExport:
[Array(11)]
0: Array(11)
0: {CustomerName: "CName1", ContactName: "contact1", ContactEmail: "email1#example.com", SubdomainName: "domain1", Region: "USA", …}
1: {CustomerName: "CName2", ContactName: "contact2", ContactEmail: "email2#example.com", SubdomainName: "domain2", Region: "USA", …}
2: {CustomerName: "CName3", ContactName: "contact3", ContactEmail: "email3#example.com", SubdomainName: "domain3", Region: "USA", …}
3: {CustomerName: "CName4", ContactName: "contact4", ContactEmail: "email4#example.com", SubdomainName: "domain4", Region: "USA", …}
4: {CustomerName: "Sudhakar", ContactName: "contact5", ContactEmail: "email5#example.com", SubdomainName: "domain5", Region: "USA", …}
5: { …}
My Javascript:
$scope.doExport = function(list){
var sheet_name = 'clients.xlsx'
var arrayToExport = {};
var arrData = [];
$scope.list = list;
var i = 0;
angular.forEach($scope.list, function(value, key){
var status = (value.status == 0) ? 'Pending' : 'Active';
var region = value.region;
region = region.toUpperCase();
var initial = value.subscr_end_date.split(/\-/);
var finalDate = [ initial[1], initial[2], initial[0] ].join('/');
//console.log( finalDate );
arrData[i] = {CustomerName:value.client_info.first_name,ContactName:value.client_info.last_name, ContactEmail:value.client_info.email,SubdomainName:value.sub_domain_name,Region:region,Status:status,SubscriptionEndDate:finalDate
};
i++;
});
arrayToExport = [arrData];
console.log(arrayToExport);
alasql('SELECT * INTO XLSX("'+sheet_name+'",{headers:true}) FROM ?', arrayToExport);
}

Related

Create nested JSON object fails

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

how to merge 2 arrays in angular 7 typescript

In angular 7 projects for a specific component I have to get data from wp site and dotnet site via api.
From wp api I am getting data as(console log data ):
(2) [{…}, {…}]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
length: 2
__proto__: Array(0)
From dotnet api I am getting data as(console log data):
(5) [{…}, {…}, {…}, {…}, {…}]
0: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
1: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
2: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
3: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
4: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 5
__proto__: Array(0)
Now I need to merge these 2 array, shuffle the array element and show it.
What I have done so far:
public merge_array : Array<{ }> = [];
/* wp api */
this.accountService.getKeynote( wp_params ).then( ( response: any ) => {
this.merge_array ? this.merge_array : [];
this.wp_data_array = response.data;
for ( let value of this.wp_data_array ) {
this.merge_array.push( value );
};
});
/* dot net api */
this.accountService.getConferences( params ).then( ( dotnetresponse: any ) => {
if ( dotnetresponse.status == 'Ok' ) {
this.merge_array ? this.merge_array : [];
this.dotnet_data_array = dotnetresponse.conferences;
for ( let value of this.dotnet_data_array ) {
this.merge_array.push( value );
};
}
});
But when I console log 'merge_array' here the result is:
[]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
2: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
3: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
4: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
5: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
6: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 7
__proto__: Array(0)
The length of merge array is coming as 0. I am not able to solve this. What am I doing wrong regarding array initialization or array push.
Any help/suggestions are welcome.
It is no surprise that the array will be empty, because the returning of Promises operates asynchronously. Hence, both arrays will be empty at the point when you log the values.
What you need to do is to use Promise.all. According to the documentation,
The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.
What can do now, is to use Promise.all to resolve the promises from both requests (you can use console.log(response) to verify that the promises are indeed resolved and a value is returned), followed by using the spread syntax to merge both arrays. Then we will randomly reshuffle the array using the algorithm provided over here by Laurens Holst. This should give you the resulting shuffled array.
const getKeynote = this.accountService.getKeynote(wp_params);
const getConferences = this.accountService.getConferences(params);
Promise.all([getKeynote, getConferences]).then(response => {
//console.log(response);
const merged = [...response[0], ...response[1]];
const shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
};
shuffleArray(merged);
console.log(merged);
});
Simple Object.assign(target, source) should do the trick
Documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
To shuffle the array, use destructuring:
for (let i = target.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[target[i], target[j]] = [target[j], target[i]];
}

Append text with object values

I am getting object as:
{
Id:3233,
Topics:"topic",
TopicId:101,
Alreadyactiontaken:null,
…
}
But i need json format as below to pass on the api:
{
"Data":[
{
"Id":477,
Topics:"topic",
TopicId:101,
Alreadyactiontaken:null,
}
]
}
Thanks in advance
Then you just need to create such an object:
let value = {Id: 3233, Topics: "topic", TopicId: 101, Alreadyactiontaken: null, …}
let apiValue = { Data: [value] }
You can push your json data into array and assign a key for this. Like following in javascript.
var array = [];
var json = {Id: 3233, Topics: "topic", TopicId: 101, Alreadyactiontaken: null};
array.push(json);
var newdata = {};
newdata.data = array;
console.log(newdata);

Get only values from the array of array using angular js

I got an array from database as
[
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
Now my required answer is that should be in the following format,
[["abc",100],
["xyz",150]]
But after some coding I got an array of Array as shown below in the console
[0:[0:"abc",1:100]
1:[0:"xyz",1:150]]
Before question down / marking duplicate please read my requirement, and if its there then mark it and please post that link as per my required solution so i can get my solution from there
So any help will be great help....
You can do like this:
data = [
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
var array =[]
data.forEach(function(item){
var tmpArray = []
tmpArray.push(item.id.unitno,item.amount)
array.push(tmpArray)
})
Now you will get your required data in the array.
I don't know how you got this below code, but that's invalid Array
[0:[0:"abc",1:100] 1:[0:"xyz",1:150]]
For your desired output you can do it with JavaScript, no need angular. Just run a simple for loop.
var temp1 = [{
id: {
unitno: 'abc'
},
amount: 100
}, {
id: {
unitno: 'xyz'
},
amount: 150
}];
var eee = [];
temp1.forEach(function(el) {
eee.push([el.id.unitno, el.amount])
});
console.log('eee:', eee);
Hope this is what you needed.
var arr = [{
id : { unitno: 'abc' },
amount: 100
},{
id : { unitno: 'xyz' },
amount: 150
}];
var result = [];
for (var i = 0; i < arr.length; i++) {
var newArray = [];
newArray.push( arr[i]["id"]["unitno"] );
newArray.push( arr[i]["amount"] );
result.push( newArray );
}
console.log( result );

Can I name a new object in an array using a variable in AngularJS?

I want to create a new nested array with the name of a variable. Is this possible?
data example:
[{
varname {
name: person1name;
events : [{
firstName: person1name,
name: event1name,
date: date1
},{
firstName: person2name,
name: event2name,
date: date2
}
]
}
}]
code:
$scope.multiEvents = []
var eventCategory = $scope.event.name
$scope.multiEvents.eventCategory.name = $scope.event.firstName;
$scope.multiEvents.eventCategory.events.push($scope.event);
$scope.multiEvents.eventCategory.events.push($scope.event2);
Ended up doing this:
$scope.multiEvents = [];
$scope.multiEvent = {};
$scope.multiEvent.events = [];
$scope.multiEvent.name = $scope.event.firstName;
$scope.multiEvent.events.push($scope.event);
$scope.multiEvent.events.push($scope.event2);
$scope.multiEvents.push($scope.multiEvent);
I think I was just confused.

Resources