Join multiple strings into one single string - javascript

I have a loop that is generating a string
function jsonResponse(response)
{
var singleString = a + "," + b + "," + c + "|";
}
with console.log(singleString);
I see them all generated :
a1,b1,c1|
a2,b2,c2|
a3,b3,c3|
But how can I create a new variable allStrings that will concatenate all of these into one string? The loop is part of an ajax response that is looping through xml nodes to retrieve the data for those variables. I guess I need to make them part of an array and then join them back together for one big string?
To further clarify what I am trying to achieve is something like :
var allStrings = singleString[0] + singleString[1] + singleString[2] ;
a1,b1,c1|a2,b2,c2|a3,b3,c3|
To better explain the loop it looks like this :
$j.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function parseXml(data)
{
$j('.loader').fadeOut();
itemQueue = $j(data).find("ITEM").map( function ()
{
return {
date: $j("LAST_SCAN" , this).text(),
type : $j("PRODUCT_TYPE", this).text(),
cat : $j("CLASS_NAME", this).text(),
};
}).get();
getNextItem();
}
});
function getNextItem()
{
var item = itemQueue[0];
var singleString = item.date+ "," + item.type + "," + item.cat + "\n";
console.log( singleString );
$j.ajax({
url: s7query,
dataType: 'jsonp'
});
}
function s7jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
// run other processes when finished with checks
if (!itemQueue.length)
{
// alert ("ALL DONE");
}
}

You can use Array.join to convert an array to a string.
Example:
var arr = ['a1', 'b1', 'c1'];
console.log(arr.join(',')); // 'a1,b1,c1'

You can get rid if that loop and use:
array.join(',')
Where array is the array you want to turn in to a string separated by commas.
To join the strings together you just need to construct a string concatenation:
allStrings.concat(string1, string2, ..., stringX)

It sounds like you're making separate XHRs for independent XML nodes, in which case you may want to reconsider your approach. If possible, I would iterate over the XML nodes in their entirety and gather all necessary request data. Then you can make a single XHR (cutting down on HTTP connections, which is good!) and get a single response that could contain the entirety of the response (i.e. allStrings). It should be easier on your server and make a noticable difference on the client side in pretty much all situations.

Related

Send object array to node/Parse to Json

I'm trying to send object array to node.
If i'm sending it without stringify, i'm getting an array with the same length that i sent, but empty (["", ""]);
if i send it with JSON.stringify , this it the result:
{'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1","newShelf":"","actionType":"in","whareHouse":"Main"},{"itemNumber":"13544","currentShelf":"1B1","amount":"1","newShelf":"","actionType":"in", "whareHouse":"Main"}]': '' }
This is how i'm sending it:
for (var i=1; i<=m; i++){
itemIdTemp= document.getElementById("itemIdShell"+i).value;
shellTemp= document.getElementById("id_shell"+i).value.toUpperCase();
newShellTemp= document.getElementById("id_shell_new"+i).value.toUpperCase();
shellAmountTemp = document.getElementById("amountShell"+i).value;
itemAmount=0;
let itemData={
itemNumber:itemIdTemp,
currentShelf:shellTemp,
amount:shellAmountTemp,
newShell:newShellTemp,
actionType:direction,
whareHouse:"Main",
};
console.log(itemData);
itemsObject.push(itemData);
}
console.log(itemsObject);
$.post('/itemShell/updateMulti',
JSON.stringify(itemsObject),
function(data){
console.log(data);
});
The object contain a string of the array and i can't get it.
I tried Json.Parse(), it won't work in this case.
any suggestions?
Have a look at this example code
const jsObjectArray = [
{name: "Homer", age:56 },
{name: "Marge", age:50 },
];
const buf = JSON.stringify(jsObjectArray);
console.log("Stringified object: "+buf);
//
// Now convert it back to an object
//
const newObject = JSON.parse(buf);
console.log("Reconstituted object: "+newObject);
It's in this codepen too:
https://codepen.io/mikkel/pen/KRayye
I found the problem.
It must be declare as JSON type when post to Node, so u need to use ajax:
$.ajax({
url: '/itemShell/updateMulti',
type:"POST",
data:JSON.stringify(dataTosend),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){}
}
and i also change it to object type like this:
dataToSend={dataArr:itemsObject}
So in node it's appearing as array
My Guy work a little bit on the string before sending it
First get the string the stringify is returning
var json_string = JSON.stringify(itemsObject);
var string = json_string.replace("'", "\'");
string = '{\'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1",
"newShelf":"","actionType":"in","whareHouse":"Main"},
{"itemNumber":"13544","currentShelf":"1B1","amount":"1",
"newShelf":"","actionType":"in", "whareHouse":"Main"}]\': \'\' }';
first_str = string.split("': "); // remove the last useless chars
second = first_str[0].substring(2, first_str[0].length); // remove the first two chars
$.post('/itemShell/updateMulti', second,
function(data){
console.log(data);
});
the second should have the correct string.
GOODLUCK

Parsing string of array of array of string back to array

I have an array of arrays of strings saved in a database column as a varchar:
[["ben"],["john","mike"],["ben"]]
I want to parse the data back into an array of arrays, so I can show the data on the screen. While attempting to do this, I ran into an awkward and annoying problem:
Here's the JSON response that is generated on the server and sent back to the client:
var response = "[{\"Names\":\""+ rows[i].Names + "\"}]";
res.send(response);
Here's the client code I wrote to parse the data:
jQuery.ajax({
type: "GET",
url: ...,
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function(data) {
jQuery.each(JSON.parse(data), function(i, parsedData) {
var names = JSON.parse(parsedData.Names);
var labels = "";
for (var n = 0; n < names.length; n++) {
var label = "<label>" + names[n] + "</label>";
labels = labels + label;
}
console.log(labels);
});
});
This is the error i'm getting:
Here's the JSON validation:
How can I solve this?
There is a simple rule:
Never use string tools to create or modify JSON. No string concatenation (+), no string replace and God forbid no regex.
The only way to produce JSON is to use a JSON serializer on a data structure. And the only way to manipulate JSON is to parse it, modify the data structure, and then serialize it again. JSON itself is to be treated as a constant, for all intents and purposes.
Your server code violates that rule. Change it like this:
var responseData = [{
Names: rows[i].Names
}];
var response = JSON.stringify(responseData);
In the above, responseData is a data structure. You are free to modify it. response is derived from that. You are not free to modify it, the only thing you can do with response is to write it to the client.
Note that rows[i].Names might be JSON itself, so you end up with a double-encoded value in your response.
Provided the server sends the Content-Type: application/json header, the client can use this:
jQuery.get("...").done(function(data) {
// data is already parsed here, you don't need to parse it
jQuery.each(data, function(i, item) {
// item.Names is not yet (!) parsed here, so we need to parse it
var names = JSON.parse(item.Names);
var labels = names.map(function (name) {
return $("<label>", {text: name});
}
console.log( labels );
});
});
If you don't want to call JSON.parse() on the client, you have to call it on the server:
var responseData = [{
Names: JSON.parse(rows[i].Names)
}];
var response = JSON.stringify(responseData);

Replacing values in JSON object

I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.

Create array of arrays from JSON

I am receiving after an ajax call the following as response using in php json_encode:
"['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]", "['2013-02-27', 6]", "['2013-02-28', 6]", "['2013-03-01', 3]", ...
How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?
Edit:
function submitForm(t) {
$.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
function(response) {
var myFanRemovesData = new Array(response);
var myChart = new JSChart(chart_id, 'line');
myChart.setDataArray(myFanRemovesData);
I have to use the array of arrays to set myFanRemovesData with it
1) strip out the double-quotes ("):
var json = json.replace(/"/g, '');
2) wrap the whole thing in square brackets:
json = "[" + json + "]";
3) replace the single-quotes with double-quotes (because the singles won't parse):
json = json.replace(/'/g, '"');
4) parse the json string:
var arrays = JSON.parse(json);
Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)
Try:
var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
var cleaned = response[i].replace(/'/g, "\"");
response[i] = $.parseJSON(cleaned);
}
DEMO: http://jsfiddle.net/hu3Eu/
After this code, the response array will contain arrays, made out of the original strings.
Just example.. because you haven't provide us with any code...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
dataType: 'json',
}).done(function( responde ) {
$.each(responde, function(i, v){
alert(v.0 + ' --- ' + v.1);
});
});
If you receive and expecting json you directly can use it as array/object :)
If its array you have to make a each loop so you can access each value..

Javascript split is not a function

Hey friends i am using javascript sdk to post on users friends wall with jQuery facebook multi friend selector however i am getting this error friendId.split is not a function. Here is my code
function recommendToFriend(pic, url, friendId, fromName)
{
alert(friendId);
var friendList ;
pFriend = new Array();
pFriend = friendId.split(',');
for( x in pFriend )
{
alert(pFriend[x]);
var publish = {
method:'feed',
picture:pic,
link:url,
name:'SHARP Product Recommend',
caption: fromName + 'has recommend a product to you via Sharp Expert lounge',
};
FB.api('/'+pFriend[x]+'/feed', 'post', publish, function(resp) {
if( !response || response.error )
alert('Unable to share');
else
alert('Successfully posted to firends wall');
});
}
}
In alert box i got comma seperated friend ids so i use split function post on each users wall seperately i dont know whats wrong here please help me
Most probably friendID is already an array. If you call alert the array is converted to a string and becomes a comma separated list of values.
Note that converting an array to a string is not the same as calling JSON.stringify (where you get also brackets and double quotes around elements when they're strings)
The JavaScript split() function is for the type string ie for eg.
var friendid='1,34,67';
As VisioN says, when you alert an array you get comma separated values.
You can traverse JS Objects like this
for (var key in friendid) {
var obj = friendid[key];
for (var prop in obj) {
alert(prop + " = " + obj[prop]);
}
}
Hope this helps
alternate
for( var x in friendId )
{
alert(friendId[x]); // this would be your desired value
}

Categories