Want to turn output into an array nodejs - arrays

I have a function returning an array that looks like this:
.then(Cause.findOne(causeId).populate('admins').exec(function (err, cause) {
var ids = cause.admins.map(function(admin) {
return admin.id;
})
var join_ids = "'" + ids.join("','");
The output of console.log(join_ids);
'26c14292-a181-48bd-8344-73fa9caf65e7','64405c09-61d2-43ed-8b15-a99f92dff6e9','bdc034df-82f5-4cd8-a310-a3c3e2fe3106'
I am trying to pass the first value of the array into another function as a userId filter:
let message = {
app_id: `${app_id}`,
contents: {"en": "Yeah Buddy," + Cause.name + "Rolling Like a Big Shot!"},
filters: [{'field': 'tag', 'key': 'userId', 'relation': '=', 'value': `${join_ids}`}]
And the output of console.log(message);
{ app_id: '*****************',
contents: { en: 'Yeah Buddy,undefinedRolling Like a Big Shot!' },
filters:
[ { field: 'tag',
key: 'userId',
relation: '=',
value: '\'26c14292-a181-48bd-8344-73fa9caf65e7\',\'64405c09-61d2-43ed-8b15-a99f92dff6e9\',\'bdc034df-82f5-4cd8-a310-a3c3e2fe3106' } ],
ios_badgeType: 'Increase',
ios_badgeCount: 1 }
If I put the console.log(join_ids[0]);
2
console.log(message);
{ app_id: '*****************',
contents: { en: 'Yeah Buddy,undefinedRolling Like a Big Shot!' },
filters:
[ { field: 'tag',
key: 'userId',
relation: '=',
value: 2} ],
ios_badgeType: 'Increase',
ios_badgeCount: 1 }
My question is how do I turn the output of join_ids to become an array where indices are 0,1,2,3.
I.E.
join_ids[0] = '26c14292-a181-48bd-8344-73fa9caf65e7', join_ids[1] = '64405c09-61d2-43ed-8b15-a99f92dff6e9'
Thanks!

based on your 2nd code snippet, it looks like its already an array. to confirm this you can try to console.log the following:
console.log(join_ids.length) // if this returns zero-based length then its an array
console.log(typeof(join_ids)) // get the TYPE of the variable
console.log(join_ids[0]) // see if you can address the FIRST value individually
// for each loop over the array and console out EACH item in the array
for (var i = 0; i < join_ids.lenght; i++) {
console.log(join_ids[i]);
}
if you find that its a string, I would remove the apostrophes
yourstring = yourstring.replace(/'/g, "") // replaces all apostrophes
and the space after the commas, if present, then just wrap the value in double quotes and do
join_ids = join_ids.split(','); // makes the comma separated values an array
Fiddle example here.

Related

Insert list data over the iteration(map)

Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};

get object from array of arrays

i have an array of objects that looks like this:
invitations: Array<record> = [new record()];
interface recordMap {
value:string;
err:string
}
export class record{
number: recordMap ;
deptNumber: recordMap ;
boothNumber: recordMap ;
primaryEmail: recordMap ;
members: recordMap [];
}
my backend request body has to look like this
[
{
"number": "string",
"deptNumber": 0,
"boothNumber": "string",
"primaryEmail": "string",
"members": [
"string"
]
}
]
this is what i have tried so far
my struggle is for the members property because it is an array in the invitation array and I am trying to get only the value from it and push it to the request body array members.
the result of my code is code 400 bad request.
How can i make this object?
const invitationArray = [];
this.invitations.forEach(invitation => {
invitationArray.push({
number: invitation.number.value,
deptNumber: invitation.deptNumber.value,
boothNumber: invitation.boothNumber.value,
primaryEmail: invitation.primaryEmail.value,
members: invitation.members.forEach(number => number.value)
});
});
You could try to use array map method. From the docs:
The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.
var members = [{ value: 'value1', error: 'error1' }, { value: 'value2', error: 'error2' }, { value: 'value3', error: 'error3' }, { value: 'value4', error: 'error4' }]
console.log(members.map(member => member.value));
Try the following
const invitationArray = [];
this.invitations.forEach(invitation => {
invitationArray.push({
number: invitation.number.value,
deptNumber: Number(invitation.deptNumber.value),
boothNumber: invitation.boothNumber.value,
primaryEmail: invitation.primaryEmail.value,
members: invitation.members.map(member => member.value)
});
});
Also it appears deptNumber property is expected to be of type number. I've converted it to number as well.

Cannot output array from http get url success function onto the html

I am trying to output the result from the success function as following, but am having no luck. The code does return values for UpcomingEvents and if I output that to the html, it works, but when I am passing it onto the returnlist, it does not work.
$scope.Events = {}
$scope.returnlist = {};
var PriorID = 67;
var i = 0;
var j = 0;
//I am calling http get url function which is working fine.
.success(function (response) {
console.log(response);
$scope.Events = response;
//I am able to display Events[0].ID in html.
if ($scope.Events[0].ID == PriorID)
//The condition holds true, so it will go inside the loop. I have
confirmed that with a debugger.
{
newID = $scope.Events[0].ID;
newname = $scope.Events[0].Title;
$scope.returnlist[0] = [{ ID: newID, Name: newname }];
$scope.returnlist[1] = [{ ID: newID, Name: newname }];
//through debugger breakpoints, I have found that returnlist is
getting the correct values.
}
})
Everything works well until I try to display the values in my html. I am trying it like this.
{{returnlist[0].ID}}
I have even tried it like this:
<tr ng-repeat="data in returnlist">
<td>returnlist.ID</td>
but no luck. What am I doing wrong?
Thanks.
first you define $scope.returnlist = {}; which is an object not an array.
Then, when you add item you assign an array not an item of array:
$scope.returnlist[0] = [{ ID: newID, Name: newname }];
So your final returnlist will look like:
{0: [{ ID: newID, Name: newname }], 1:[{ ID: newID, Name: newname }],...}
an object with array value, so when you do $scope.returnlist[0].ID you will get undefined.
The right way is:
$scope.returnlist = [];//an array
//in the loop now:
$scope.returnlist[0] = { ID: newID, Name: newname };//an item not an array

Ionic 2 / 3: Number Input from Alert

I'm using Ionic 3.x on macOS.
I have the following issue:
I have an array containing a number and an array of names.
table: { number: number, names: string[] } = {
number: 0,
names: ['']
};
I want to set the number of the array using an input for the user. I stumbled upon the AlertController.
I have written the following function thing to add a number:
addTable(){
let prompt = this.alertCtrl.create({
title: 'Add Table',
subTitle: 'Enter the table number',
inputs: [{
name: 'tableNumber',
placeholder: 'Number',
type: 'number'
}],
buttons: [
{
text: 'Cancel'
},
{
text: 'Add',
handler: data => {
//this.tables.push(data);
this.table.number = data;
}
}
]
});
prompt.present();
}
But this always sets table.number to object [object]. If I write it as this.table.number = +data; it has the value NaN. The push version also doesn't work.
How do I set table.number to a number that the user put in?
The name of the input
name: 'tableNumber'
gets added as a property name to the resulting object. You can access it like this:
handler: data => {
this.table.number = data.tableNumber;
}

Want to remove an escape character from output of an array

So I have an array thats being returned by a function:
console.log(join_ids)
[ '\'26c14292-a181-48bd-8344-73fa9caf65e7\'',
'\'64405c09-61d2-43ed-8b15-a99f92dff6e9\'',
'\'bdc034df-82f5-4cd8-a310-a3c3e2fe3106' ]
I was initially able to split the array using this function:
join_ids = join_ids.split(',');
I want to try and remove the backslashes from the output and this is the function I'm using:
join_ids = join_ids.replace(/\\/g, "");
console.log(typeof(join_ids));
object
I am trying to send a notification and the parameters in it are:
let message = {
app_id: `${app_id}`,
contents: {"en": "Yeah Buddy, Rolling Like a Big Shot!"},
filters: [{'field': 'tag', 'key': 'userId', 'relation': '=', 'value': `${join_ids[0]}`}],
ios_badgeType: 'Increase',
ios_badgeCount: 1
};
The response I'm seeing is the following:
console.log(message);
{ app_id: '****************',
contents: { en: 'Yeah Buddy, Rolling Like a Big Shot!' },
filters:
[ { field: 'tag',
key: 'userId',
relation: '=',
value: '\'26c14292-a181-48bd-8344-73fa9caf65e7\'' } ],
ios_badgeType: 'Increase',
ios_badgeCount: 1 }
I want the respone to be:
value: '26c14292-a181-48bd-8344-73fa9caf65e7'
What might I be doing wrong?? Thanks!
This could be done by using a replace() with a simple regex and a tagged template literal when you're inserting the value into your message object as a template literal.
function stripEscape (strings, ...values) {
return values[0].replace(/\\`/g, '');
}
let message = {
app_id: `${app_id}`,
contents: {"en": "Yeah Buddy, Rolling Like a Big Shot!"},
filters: [{'field': 'tag', 'key': 'userId', 'relation': '=', 'value': stripEscape`${join_ids[0]}`}],
ios_badgeType: 'Increase',
ios_badgeCount: 1
}
If you do not want to use the tagged template literal, you can chain the replace on your template literal paramter.
let message = {
app_id: `${app_id}`,
contents: {"en": "Yeah Buddy, Rolling Like a Big Shot!"},
filters: [{'field': 'tag', 'key': 'userId', 'relation': '=', 'value': `${join_ids[0].replace(/\\`/g, '')}`}],
ios_badgeType: 'Increase',
ios_badgeCount: 1
}
Hope this helps get what you were wanting, if you run into problems with it...let me know as I am still learning how to use ES6 features effectively.

Resources