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.
Related
I think Im misunderstanding something here - I normally work in PHP and think I'm missing something small. My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,". It seems to me my tmp array might be emptied somewhere or the scope gets reset for some reason. I'm using this as coordinates from a table where you can select table rows and posting to a webservice but my array seem to be erroneous.
var length = $("#arrayCount").html();
var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var col = getSelectedColumn(); //for example sake lets say "B" is the selected column
var row = getSelectedRow(); //selected rows will be from "11" - "16"
var columnIndexStart = letters.indexOf(col[0]);
var tmp = [];
for(var i = row[0]; i <= row[1]; i++) //rows[0] = 11 and rows[1] = 16
{
tmp[i] = [];
for(var j = columnIndexStart; j < letters.length; j++) //columns and starts at index 1 if we work with "B"
{
var val = $("#" + i + "_" + letters[j]).html(); //using the row and letters as the associated DOM elements ID. Easier to retrieve it's HTML then.
if(val != undefined)
{
console.log("Index [" + i + "]['" + letters[j] + "'] = " + val); //works perfectly and prints as it should.
tmp[i]['"'+letters[j]+'"'] = val; //using quotes to save letters? Is this preferred?
}
}
}
console.log('Final Array: ' + tmp); //empty??
console.log('Final Array: ' + tmp[14]['G']); //testing HTML output. But is undefined.
return tmp;
Any help will be greatly appreciated.
Edited:
Example of console output.
My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,"
With non-numeric index you are setting the field of object and not the element for index.
If you will have two-dimensional numeric array with numeric indices like the following:
var tmp = [[1,2,3], [1,2,3]];
after console.log('tmp = ' + tmp); you will obviously get the output string like:
tmp = 1,2,3,1,2,3
Because when you are trying to convert array to string it converts it elements to string and represent them with a commas.
However when you are trying to set element with non-numeric index, you are setting the field of this object.
var tmp = [];
tmp['A'] = 123;
console.log("tmp = " + tmp); // tmp =
console.log(tmp.A); //123
So, console.log in your case works good - it is serializing all elements of two-dimensional array. But no one array of the second level does not have stored values, it has only fields, which are not included in the string representation of array.
You are getting a set of commas, because each sub-array of tmp array does not contains any element, so it's string representation is an empty string. Each sub-array contains the required data into it's fields.
When you are performing sum operation of string and object you are forcing object to convert to string representation. Instead of this it is recommended to use console.log(yourObj) - it will log the whole object without converting it to string.
//using quotes to save letters? Is this preferred?
No, "A" and A are different identifiers.
var s = new Object();
s['"A"'] = 123;
console.log(s['A']); //undefined
console.log(s['"A"']); //123
Additionally, if you will set fields with quotes - you can not get the field in normal style:
console.log(s."A"); //syntax error : expected identifier after '.'
You can also just do this (use comma, not plus):
console.log('Final Array: ', tmp); //empty??
console.log('Final Array: ', tmp[14]['G']);
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
I need to serialize this string into a multidimensional array using JSON. How would you do it?
{frmb[0][cssClass]=textarea&frmb[0][required]=true&frmb[0][values]=para&frmb[1][cssClass]=radio&frmb[1][required]=true&frmb[1][title]=rdo&frmb[1][values][2][value]=one&frmb[1][values][2][baseline]=true&frmb[1][values][3][value]=two&frmb[1][values][3][baseline]=false&frmb[2][cssClass]=input_text&frmb[2][required]=false&frmb[2][values]=text&frmb[3][cssClass]=checkbox&frmb[3][required]=true&frmb[3][title]=chk&frmb[3][values][2][value]=chk+1&frmb[3][values][2][baseline]=true&frmb[3][values][3][value]=chk+2&frmb[3][values][3][baseline]=false&frmb[4][cssClass]=select&frmb[4][required]=false&frmb[4][multiple]=true&frmb[4][title]=sel&frmb[4][values][2][value]=sel1&frmb[4][values][2][baseline]=true&frmb[4][values][3][value]=sel2&frmb[4][values][3][baseline]=false&form_id=undefined}
EDIT:
The multidimensionality is really screwing me up on converting this string into JSON. I tried stripping out the brackets to get a list of indices for the array, but rebuilding the array in a useful manner has been the biggest challenge.
So I have been doing:
private static List<string> StripBrackets(string input)
{
var ret = new List<string>();
var indx = 0;
do
{
input = input.TrimStart('[');
indx = input.IndexOf(']');
if(indx !=-1)
{
var newVal = input.Substring(0, indx);
ret.Add(newVal);
input = input.Remove(0, indx+1);
}
} while (indx != -1);
//-- this is where I bonked
string[,] results = new string[ret.Count, 23];
foreach (var r in ret)
{
}
return ret;
}
I've been grinding on this for a long time - hence the tired/limited question. It started to feel like I was doing this the "hard way" and wanted to see if anyone enlightened had any better ideas. TIA
Expanding on #ratchetfreak's comment:
var str = "{frmb...";
//sanitize string
str = str.substring(1, str.length-1); //remove braces
str = str.replace(/\[([a-z]+)\]/gi, '["$1"]'); //enclose non-numeric keys in double quotes
str = str.replace(/=([^&]+)/g, '="$1"'); //enclose values in double quotes
str = str.replace(/"(true|false)"/g, "$1"); //remove double quotes around boolean values
str = str.replace(/&/g, ";"); //replace all ampersands with semi-colons
//initialize "frmb"
var frmb = [];
for (var i = 0; i < 5 /* a guess as to how long "frmb" will be */; i++){
var values = [];
for (var j = 0; j < 5 /* a guess as to how long each "values" field will be */; j++){
values.push({});
}
frmb.push({values:values});
}
//evaluate as Javascript
eval(str);
//marshal to string
var result = JSON.stringify(frmb);
The part that makes this solution difficult to make general-purpose is that you need to initialize "frmb". For example, you can't call frmb[0].cssClass without first initializing frmb to an array and then adding an object to that array with push(). So, you need to estimate how large you think frmb will be, as well as how large each values sub-array will be.
How to get separate values of array in javascript?
in one page:
var c=new Array(a); (eg: a={"1","2"}) window.location="my_details.html?"+ c + "_"; and in my_details.html :
my_details.htm:
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + decodeURIComponent(list) + "llll " );
But i am not able to get individual array value like list[0] etc
How to get it?
thanks
Sneha
decodeURIComponent() will return you a String; you need to do something like:
var delim = ",",
c = ["1", "2"];
window.location = "my_details.html?" + c.join(delim);
And then get it back out again:
var q = window.location.search,
arrayList = (q)? q.substring(1).split("_"):[],
list = [arrayList];
arr = decodeURIComponent(list).split(delim);
This will use the value of delim as the delimiter to make the Array a String. We can then use the same delimiter to split the String back into an Array. You just need to make sure delim is available in the scope of the second piece of code.
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.