Creating string out of object in JavaScript - javascript

I am trying to assemble a certain string out of a JavaScript object and am having some problems.
I created a function that takes the object and should return the string. The initial object looks like so:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
And I would like the string to spit out this:
"Topics~~Other|Topics~~New1|Other~~try this|Other~~this also"
Here is what I have now:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
function transformObjectToString(activeFilters) {
var newString = "";
var checkFilterGroups = function(filterTopic) {
activeFilters[filterTopic].map(function(selectedFilter) {
var tempString = filterTopic + "~~" + selectedFilter + "|";
console.log("check string", tempString);
newString.concat(tempString);
});
}
for (var filterGroup in activeFilters) {
checkFilterGroups(filterGroup);
}
return newString;
}
console.log(transformObjectToString(testObject));
The temp string seems to be formatted correctly when I check the log, but, for whatever reason, it looks like the concat is not working as I assumed it would.

You should be able to just use += as this is just string concatenation. Then, all you must do is strip the last character. Here's a JSFiddle with the change https://jsfiddle.net/tfs98fxv/37/.

You can use .join('|')
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
function transformObjectToString(activeFilters) {
var strings = [];
var checkFilterGroups = function(filterTopic) {
activeFilters[filterTopic].map(function(selectedFilter) {
var tempString = filterTopic + "~~" + selectedFilter;
strings.push(tempString);
});
}
for (var filterGroup in activeFilters) {
checkFilterGroups(filterGroup);
}
return strings.join('|');
}
console.log(transformObjectToString(testObject));

newString = newString.concat(tempString);
this works too.
edit: how this works is, at first newString is set to null so null + tempstring at first loop, and then the newSting is set to a value, value + tempString on second loop and so on. finally you have the concatinated string in one variable which you will be returning.
edit:edit:
Also what #jfriend00 said in the comments, ditto
.concat() returns a new string so newString.concat(tempString); is not
accomplishing anything because you don't assign the result back to
newString. Remember, strings in Javascript are immutable so any
modification always creates a new string

Related

Oracle Apex changing a String of a object

So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Removing two words from text from string javascript

Hey I'm looking at removing words from a string, thing is the word to replace could be two different words.
e.g.
foo = "stringtest";
id = foo.replace('string', '');
or
foo = "paragraphtest";
id = foo.replace('paragraph', '');
at the moment I've approached the problem as so.
foo = "paragraphtest";
id = foo.replace('paragraph', '');
id = foo.replace('string', '');
I know this code could easily be improve but I don't know how :( thanks for your assistance.
Like this?
var foo = ["paragraph","string"];
var id = foo.replace(new RegExp(foo.join("|"),""));
The above creates array with strings you want to replace and joins it with | in RegExp constructor and replaces the match with empty string.
if(foo.indexOf("ph") > -1)
id = foo.replace('paragraph', '');
else
id = foo.replace('string', '');
Something like this maybe. Which will also give you the flexibility to modify what you replace each string with.
var replacementCharacters = [
{
searchString: "paragraph",
replacementString: ""
},
{
searchString: "string",
replacementString: ""
}
];
function runReplacement(str) {
var returnValue = str;
for (var i = 0; i < replacementCharacters.length; i++) {
returnValue = returnValue.replace(replacementCharacters[i].searchString, replacementCharacters[i].replacementString);
}
return returnValue;
}
var foo = "paragraphtest";
var id = runReplacement(foo);
Here is a demo http://jsfiddle.net/RfKt4/

Concat JS not working

var myjson = '{"name": "cluster","children": [';
for (var i = 0; i < unique.length; i++)
{
var uniquepart = '{"' + unique[i] + '"';
myjson.concat(uniquepart);
var sizepart = ', "size:"';
myjson.concat(sizepart);
var countpart = count[i] + '';
myjson.concat(countpart);
if (i == unique.length) {
myjson.concat(" },");
}
else {
myjson.concat(" }");
}
}
var ending = "]}";
myjson.concat(ending);
console.log(myjson);
Does anyone know why this string doesn't concat properly and I still end up with the original value?
The concat() method is used to join two or more strings.
Definition and Usage
This method does not change the existing strings, but returns a new string containing the text of the joined strings.
Ref: http://www.w3schools.com/jsref/jsref_concat_string.asp
For example:
myjson = myjson.concat(uniquepart);
OR
myjson += uniquepart;
A javascript string is immutable so concat can only return a new value, not change the initial one. If you want to append to a string you have as variable, simply use
myjson += "some addition";
string.concat() does not modify the original string it instead returns a new string.
In order to modify it you would need to perform:
string = string.concat('fragment');
Strings are immutable.
.concat() returns a new string, which you ignore.

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

Categories