Javascript create a mapping of array values - javascript

I am working on a project where I give a user the ability to create their own email templates and insert tags into them as placeholder values that will eventually replaced with content.
The tags are in the format of [FirstName] [LastName]
I am trying to figure out the best approach to create a function that maps these tags to their values.
For example (Psuedo code):
function convertTags(message){
// Convert all instances of tags within the message to their assigned value
'[FirstName]' = FirstNameVar,
'[LastName]' = LastNameVar
// Return the message with all tags replaced
return message;
}
I assume I could do something like the following:
function convertTags(message){
message = message.replace(/[FirstName]/g, FirstNameVar);
message = message.replace(/[LastName]/g, LastNameVar);
return message;
}
I am just trying to come up with a clean way to do this, preferably in an array/mapping style format that I can easily add to.
Any recommendations on achieving this?

You're on the right lines. You just need to generalise your REGEX to match all params, not specifically 'firstname' or some such other hard-coded value.
Let's assume the replacers live in an object, replacers.
var replacers = {
'foo': 'bar',
'something-else': 'foo'
};
And here's our template:
var tmplt = 'This is my template [foo] etc etc [something-else] - [bar]';
For the replacement, we need iterative replacement via a callback:
tmplt = tmplt.replace(/\[[^\}]+\]/g, function(param) { //match all "[something]"
param = param.replace(/\[|\]/g, ''); //strip off leading [ and trailing ]
return replacers[param] || '??'; //return replacer or, if none found, '??'
});
The value of tmplt is now
This is my template bar etc etc foo - ??

Let's say you have an object like this:
var tagMapper: {};
In this object you can add anything you want as key-value pairs, example:
function addTag(key, value){
key = "__prefix__" + key;
tagMapper[key] = value;
}
addTag("key1", "value1");
The difference between an object and an array in javascript is that one uses named indexes while the other uses numbered indexed to set and retrieve data.
Now every time your user adds a new tag, you just add a new key-value pair to this object by calling the addTag function, then to replace those keys in your template just loop over the object as such:
for (var key in tagMapper) {
if (tagMapper.hasOwnProperty(key)) {
template = template.replace(key, tagMapper[key]);
//key here has value "__prefix__key1" and maps to "value1" from our example
}
}
The prefix was added to ensure the script doesn't replace an undesirable string from our template. Your tag format may be sufficient if you are sure the template doesn't contain any [] tags containing the same key as one in the tagMapper object.

Related

replace() on variable not working

replace() is not working on a variable I've created representative of a bunch of names I'm deriving from a JSON object in a loop.
I understand strings are immutable in JS. I believe I have ruled that out.
for (object in Object.keys(json)) {
console.log(json[object]["senderProfile"]["name"])
var name_ = String(json[object]["senderProfile"]["name"])
var name = name_.replace(',', '')
names.push(name+"<br>")
}
document.getElementById("json_out").innerHTML = names;
The HTML that is rendered has commas in between each name. Not sure what to make of it.
names is an array. You are implicitly converting the array to a string. By default, array members are separated by comma. Simple example:
console.log('' + [1,2,3])
You can join array members with a custom separator by calling .join:
console.log('' + [1,2,3].join(''))
It may be possible to simplify your code, but not without knowing what the value of json or json[object]["senderProfile"]["name"] is. However, instead of appending <br> to the name, you could use it as the element separator:
var names = Object.keys(json)
.map(key => json[key]["senderProfile"]["name"]);
document.getElementById("json_out").innerHTML = names.join('<br>');

Split string using regex expression

I need to split a dynamic string. The string may look like the one below having Code, Name and EffectDate. or it may have only (Code and Name) or (Code and EffectDate) or (Name and EffectDate). You got the point right.
{"Code":{"value":"1"},"Name":{"value":"Entity1"},"EffectDate":{"value":"23/11/2016"}}
to
...
this.data[0].key ='Code'; \\something like this (desired result)
this.data[0].value = '1';
this.data[1].key = 'Name';
this.data[1].value = 'Entity1';
this.data[2].key = 'EffectDate';
this.data[2].value = '23/11/2016';
What i did in my code :
...
filters:string;
data:string[];
...
this.data = this.filters.split("\b(?:(?!value)\w)+[a-zA-Z0-9/]\b");
console.log(this.data);
I used this pattern \b(?:(?!value)\w)+[a-zA-Z0-9/]\b but still couldn't get the desired result. The this.filter always returns only one array with the same string. Any advice would be helpful. Thank you.
Update #1:
I'm using PrimeNg extension for datatable and i get event as a parameter. In that, event.filters returns me a list of filter objects. I cannot send the object to the service, it needs to be in the format to work with the service.
That looks like JSON. What's to stop you from just doing data = JSON.parse(content) and iterating over the key-values using keys(data) for keys and data[i]["value"] for values?
Try something like this:
var data = [];
for(var i in event.filters){
data.push({"key": i, "value": event.filters[i].value});
}

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

Dynamically add variable name as part of object in Javascript/jQuery

I'm trying to create an object which references a number of forms which I can JSON.stringify() to send through to a validation script with a single AJAX request, but I can't seem to properly name the array inside the object, which should be an incrementing count as the number of arrays (forms) increases.
i.e.
var images = new Object();
var i = 0;
// loop through every form
$('form').each(function() {
var form = $(this);
images[i].name = form.find('input[name="name"]').val();
images[i].description = form.find('textarea[name="description"]').val();
// etc.
i++;
});
So, when complete after say two to three iterations (that is, it's gone through two-three forms), I have a Javascript object similar to this (written in pseudocode, I'm not exactly too sure how it's actually outputted):
images {
0 {
name : 0thImageNameValueHere,
description : 0thImageDescripValueHere,
etc : etc
}
1 {
name : 1stImageNameValueHere,
description : 1stImageDescripValueHere,
etc : etc
}
}
But, right now, Firebug is giving me a SyntaxError: missing ; before statement error, centered around this line:
images[i].name = form.find('input[name="name"]').val();
Now, I can change the 'value' of images[i].name to anything I like (images[i].name = 'yes') and I still get the same error. Syntactically I'm not missing any semi-colons, so it can't be that. Is it possible I'm not declaring my object correctly?
Images is an array ([]). Your syntax does not comply with this situation (you expect an object). Create an object for each item in the array, then you can assign values to the attributes of this object.
Also, you can just make use of the index parameter provided by jQuery, you don't have to create your own iterator.
This does what you want:
var images = []; // create an array
$('form').each(function( index ) {
var form = $(this);
// create object with {} object notation
var image = {
name: form.find('input[name="name"]').val(),
description: form.find('textarea[name="description"]').val()
};
images[index] = image; // append object in array position index;
}
See for more info on objects the JSON WIKI.
See for more info on arrays W3Schools.
I don't know about any missing semi colon, but you need to create an object at images[i] before you assign any properties on it. Ie try this:
images[i] = {
name: get('input[name="name"]').val(),
description: get('textarea[name="description"]').val()
};
You can also use the index parameter supplied by each():
$('form').each(function(i) { ... }

Javascript: How to convert JSON dot string into object reference

I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.

Categories

Resources