Split string using regex expression - javascript

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

Related

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

Javascript create a mapping of array values

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.

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.

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

Javascript is passing an Array of Objects instead of an Array of Arrays

I'm passing a Javascript Array() to Flash via FlashVars but Flash complains. Can you guys point me what am I doing wrong here?
javascript code
// array with the user defined cities
var usercities = new Array(
{'nome':"London", 'lat':51.5002, 'long':-0.1262 },
{'nome':"NYC", 'lat':51.5002, 'long':-0.1262 }
);
flashvars.newcities = usercities;
flash code
// this array is pre-populated so if the users doesn't enter data this is shown
var cities:Array = new Array(
{ nome:"London", lat:51.5002, long:-0.1262 },
{ nome:"NYC", lat:40.7144, long:-74.0060 }
);
// gets FlashVars
var newcities:Object = LoaderInfo(this.root.loaderInfo).parameters.newcities;
if(newcities != null) {
cities = newcities;
};
Doesn't work. I need to have the cities array on the Flash Side exactly as it is. On the Javascript side all code can change.
Thank you for your help.
JavaScript does not have associative arrays like other languages. In order to have named indexes, you have to use an object. An array that is assigned a value with a named index will be converted to an object.
In order to do this, you may need to change your Flash code. As meder said, serializing your array is your best bet. I'd suggest a JSON encode in the JavaScript and a decode in the Flash.
Well you can just manually make them arrays. Something like this:
var usercities = [];
usercities[0] = [];
usercities[0]["nome"] = "London";
usercities[0]["lat"] = 51.5002
usercities[0]["long"] = -0.1262
usercities[1] = [];
usercities[1]["nome"] = "NYC";
usercities[1]["lat"] = 51.5002
usercities[1]["long"] = -0.1262
Though I think it is all the same but flash may be seeing it differently.
Ended up passing the values as this:
javascript
var cities = new Array(
Array("London", 51.5002, -0.1262),
Array("NYC", 40.7144, -74.0060),
);
That flash gets as a pure string.
"London",51.5002,-0.1262,"NYC",40.7144,-74.0060
I then exploded the string and converted to Array. It's a bit dirty but in the end works. As long as the Array always has 3 items per row and no item has a comma.
Hope this may help someone.

Categories

Resources