Want to remove an escape character from output of an array - arrays

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.

Related

update one element of array inside object and return immutable state - redux [duplicate]

In React's this.state I have a property called formErrors containing the following dynamic array of objects.
[
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
Let's say I would need to update state's object having the fieldName cityId to the valid value of true.
What's the easiest or most common way to solve this?
I'm OK to use any of the libraries immutability-helper, immutable-js etc or ES6. I've tried and googled this for over 4 hours, and still cannot wrap my head around it. Would be extremely grateful for some help.
You can use map to iterate the data and check for the fieldName, if fieldName is cityId then you need to change the value and return a new object otherwise just return the same object.
Write it like this:
var data = [
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
var newData = data.map(el => {
if(el.fieldName == 'cityId')
return Object.assign({}, el, {valid:true})
return el
});
this.setState({ data: newData });
Here is a sample example - ES6
The left is the code, and the right is the output
Here is the code below
const data = [
{ fieldName: 'title', valid: false },
{ fieldName: 'description', valid: true },
{ fieldName: 'cityId', valid: false }, // old data
{ fieldName: 'hostDescription', valid: false },
]
const newData = data.map(obj => {
if(obj.fieldName === 'cityId') // check if fieldName equals to cityId
return {
...obj,
valid: true,
description: 'You can also add more values here' // Example of data extra fields
}
return obj
});
const result = { data: newData };
console.log(result);
this.setState({ data: newData });
Hope this helps,
Happy Coding!
How about immutability-helper? Works very well. You're looking for the $merge command I think.
#FellowStranger: I have one (and only one) section of my redux state that is an array of objects. I use the index in the reducer to update the correct entry:
case EMIT_DATA_TYPE_SELECT_CHANGE:
return state.map( (sigmap, index) => {
if ( index !== action.payload.index ) {
return sigmap;
} else {
return update(sigmap, {$merge: {
data_type: action.payload.value
}})
}
})
Frankly, this is kind of greasy, and I intend to change that part of my state object, but it does work... It doesn't sound like you're using redux but the tactic should be similar.
Instead of storing your values in an array, I strongly suggest using an object instead so you can easily specify which element you want to update. In the example below the key is the fieldName but it can be any unique identifier:
var fields = {
title: {
valid: false
},
description: {
valid: true
}
}
then you can use immutability-helper's update function:
var newFields = update(fields, {title: {valid: {$set: true}}})

Format formly form field

I want to format a field when the data finally updates the model. The number usually comes back with a decimal point so what I want to be able to do is format it to no decimal point number (parseNumber function does that).
e.g. vm.model.total = 34.54
I want to format this number to 34 on the fly.
I can't make it work...
vm.fields = [
{
className: 'row',
fieldGroup: [
{
className: 'col-xs-12',
key: 'total',
type: 'input',
templateOptions: {
wrapperClass: 'row',
labelClass: 'col-xs-9 col-sm-3',
dataClass: 'col-xs-3 col-sm-2 col-sm-offset-right-7',
label: 'Total',
disabled: true
},
formatters: [parseNumber(vm.model.total, 0)]
}
]
}
];
Your example does not match the examples in the documentation
Your argument to formatters field is incorrect. That field is expecting a function, NOT THE RESULT of the function, which is what you have defined here.
You should either use an anonymous function or a named function:
formatters: [function(value){ return parseNumber(value, 0); }]
or
formatters: [removeDecimal]
//...
function removeDecimal(value) {
return parseNumber(value, 0)
}
This is a working example from their own documentation which I have added a formatter to the first name field: https://jsbin.com/hapuyefico/1/edit?html,js,output

angular schema form: enum translation

I have a select, its schema looks like this:
type: {
type: 'string',
enum: ['Event', 'BusinessEvent', 'ComedyEvent', ... ],
default: 'Event'
}
and its form def like this:
{
key: 'type',
title: $translate.instant('templates.forms.event.type'),
feedback: false
}
I'm using angular translate for the i18n. The select works flawlessly, however I haven't found a way to translate the actual items in the enum. Is there a way to do this?
I was thinking of something in the form def like this:
{
key: 'type',
title: $translate.instant('templates.forms.event.type'),
feedback: false,
showAs: function(value) {
return $translate.instant('templates.forms.event.' + value);
}
}

Want to turn output into an array nodejs

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.

Using angular-translate with formly in a select form

I'm trying to use angular-translate to translate the data from a select input on a form made formly, but I can't make it work properly.
Basically, when using angular-translate for other types of input, I would have to do something like
'templateOptions.label': '"NAME" | translate',
'templateOptions.placeholder': '"NAME" | translate'
following this pattern, I've tried to put my data like this:
"templateOptions.options": [
{
"name": "{{ 'OPT1' | translate }}",
"id": 1
},
{
"name": "{{ 'OPT2' | translate }}",
"id": 2
}
]
But that gives me nothing on the dropdown menu. Can someone give me any directions here?
The complete code can be found on the link http://output.jsbin.com/horawaqaki/
Thanks for the help!
In this case you can use $translate service inside your controller. This service can return you translated values, but it is asynchronous operation. Because of this you should add some flag in your controller in order to show form only when you receive this translations (in this example I'm going to use vm.areFieldGenerated and then show/hide form and element with ng-if).
So, basically you should pass an array of localization keys and $translate service will return you the following object:
{
'NAME': 'Name',
'OPT1': 'Working!',
'OPT2': 'Working indeed!'
}
And after that you are able to use this value to localize your field title or options.
Your function for generating fields and assigned translated values to the options will look like this:
// variable assignment
vm.env = getEnv();
vm.model = {};
vm.options = {formState: {}};
vm.areFieldsGenerated = false;
generateFields();
// function definition
function generateFields() {
$translate(['NAME', 'OPT1', 'OPT2']).then(function(translationData) {
vm.fields = [
{
key: 'item',
type: 'select',
templateOptions: {
valueProp: 'id',
labelProp: 'name',
options: [
{name:'Not working!', id: 1},
{name:'Not working indeed!', id: 2}
]
},
expressionProperties: {
'templateOptions.label': transationData['NAME'],
'templateOptions.options': [
{
name: translationData['OPT1'],
id:1
},
{
name: translationData['OPT2'],
id:2
}
]
}
}
];
vm.originalFields = angular.copy(vm.fields);
vm.areFieldsGenerated = true;
});
}
I've created working example here.
More examples with $translate on angular-translate.github.io.

Resources