Adding string to an array filled with arrays - javascript

I have this array object that contains arrays:
var webApps = [
['leave empty']
];
I'm ajaxing in some content and the end ajax resulting string will be something like this:
ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
My question is, how do I take the returned string and add it to the webApps array?

As #Bergi pointed out, it would probably be a good idea to make your ajax call return valid JSON. If thats not something you have control over, then you need to turn it into valid JSON, parse it, and concat to the webApps array:
var webApps = [
['leave empty']
];
var ajaxResult = ',["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]';
//strip the comma
ajaxResult = ajaxResult.substring(1);
//surround with []
ajaxResult = "[" + ajaxResult + "]";
//parse
ajaxResult = JSON.parse(ajaxResult);
//and concat
webApps = webApps.concat(ajaxResult);

First transform the result into something that is parseable (I hope no other quirks is necessary):
var jsonStr = "["+ajaxResult.slice(1)+"]";
// [["Alex","Somewhere, NY, 11334"],["Zak","Cherryville, FL, 33921"]]
// would be better if it looked like that in the first place
Now we can parse it, and push the single items on your array:
var arr = JSON.parse(jsonStr);
webApps.push.apply(webApps, arr);
We could've used a loop as well, but push can take multiple arguments so it's easier to apply it.

The following works if the browser supports JSON.
var webApps = [
['leave empty'],['one']
];
var str = JSON.stringify(webApps);
// "[["leave empty"],["one"]]"
str = str.substr(0, str.length-1);
//"[["leave empty"],["one"]"
//var arr = eval(str + ajaxResult + "]");
// more secure way
var arr = JSON.parse(str + ajaxResult + "]");

webApps = eval("[['"+(webApps[0]).toString()+"']"+ajaxResult+"]");
It's weird, but solve your question.

If ajax result is a string, you can convert it to object and add each property to webapps var.
var data = eval('(' + ajaxResult + ')'); // data is a javascript array now, do anything you want

Related

Is there a way to replace text from a JSON object after it has been stringified?

I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");

Print Object like console.log (with a lot of information) in javascript

I need to send an email that contains the console.log output of a JS object. Here a code example:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
console.log(array_multi);
In my console result like this:
Is there some method to get this output in plain text, or should I write a custom parsing function?
If you are using JSON.stringify, you'll get the complete data, however there are a few downsides:
Arrays string properties, functions and other data structures get ignored completely (therefore serializing your data as is won't work¹)
circular references fail to serialize
There is no way to see inheritance from that
In your case you could do:
let array_multi = {};
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
// logs as object
console.log(array_multi);
console.log(typeof array_multi);
// parse and convert to string
console.log(JSON.stringify(array_multi));
console.log(typeof JSON.stringify(array_multi));
In Node.js you've got another option, which is util.format, which will return the same content as a string that you can see in the Node.js console. While it does give you a great insight into the different datatypes and relationships, it cannot show you the same infinite tree that an interactive console is able to show, so it will only show you a small part of the big picture.
¹: Your array_multi should actually be an object, not an array, as arrays should only have numeric keys.
After a lot of search the right method is write a custom function (chrome have once inside dev tools core)
here the solution:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
function print_js_element(elm, show_content = false){
let output_res = "{\n";
let object_keys = Object.keys(elm);
object_keys.some(function(key,index) {
output_res += "\t" + key + ": (" + elm[key].length + ")";
if(show_content){
output_res += " " + JSON.stringify(elm[key]);
}
output_res += "\n";
});
output_res += "\n}";
return output_res;
}
console.log(print_js_element(array_multi,false));
console.log(print_js_element(array_multi,true));
Covert this array into an object first:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
let arrObj = {...array_multi};
console.log(JSON.stringify(arrObj));

JSON conversion issue

I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');

Convert a javascript string into a 2-dimensional array

I have this data coming from a REST method using jquery's getJSON method.
"[Date.UTC(2010,0,0,0,0,0,0), 157],[Date.UTC(2010,0,0,0,0,420,1), 157],[Date.UTC(2010,0,0,0,0,420,2), 282],[Date.UTC(2010,0,0,0,0,600,3), 282],[Date.UTC(2010,0,0,0,0,600,4), 125],[Date.UTC(2010,0,0,0,0,900,5), 125],[Date.UTC(2010,0,0,0,0,900,6), 282],[Date.UTC(2010,0,0,0,0,2100,7), 282],[Date.UTC(2010,0,0,0,0,2100,8), 125],[Date.UTC(2010,0,0,0,0,2400,9), 125],[Date.UTC(2010,0,0,0,0,2400,10), 295],[Date.UTC(2010,0,0,0,0,3600,11), 295],[Date.UTC(2010,0,0,0,0,3600,12), 125],[Date.UTC(2010,0,0,0,0,3900,13), 125],[Date.UTC(2010,0,0,0,0,3900,14), 288],[Date.UTC(2010,0,0,0,0,5100,15), 288],[Date.UTC(2010,0,0,0,0,5100,16), 125],[Date.UTC(2010,0,0,0,0,5400,17), 125]"
It comes back as a string. I need to parse it into a two dimensional array. Each item in the array should have a date and a value.
I also have full control over the REST method, so I could change the way the data returns. I'm interested in making this as fast as possible.
Here's what we are doing now which I think could be improved:
var jqxhr = $.getJSON(getDataURL, function(dataResult) {
var result = dataResult;
result =result.replace(/\]\,\[/g, ']:[');
result = result.replace(/\)\,/g, ');');
var tempArray = result.split(':');
var myarray = new Array();
myarray[0] = new Array(2); // Make the first element an array of two elements
for(i = 0; i < tempArray.length; i ++)
{
myarray[i] = tempArray[i].split(';');
myarray[i][1] = myarray[i][1].replace(/\"/g,'');
myarray[i][1] = myarray[i][1].replace(/\]/g,'');
myarray[i][0] = myarray[i][0].replace(/\[/g,'');
}
})
As much as I'm going to get flack for this (eval tends to be a security risk), I would just do
var myarray = eval("[" + result + "]");
You should use JSON to return data from your server to your JS script. That will be pretty easier to manipulate it as an array.

Create JSON string from javascript for loop

I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.
Two problems:
You want an object, so the JSON string has to start with { and end with }.
There is a trailing , which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
Change var edited = ""; to var edited = "{"; to start your JSON string with a {
Add edited = edited.slice(0, -1); after the for loop to remove the trailing comma.
Add edited += "}"; after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify) by making an object with a for loop, adding properties by using POST[i].name as a key and POST[i].value as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1 and ending with index POST.length-2, therefore excluding indices 0 (the first value) and POST.length-1 (the last value). Is that what you really want?
//dummy data
var post=[{name:'name1',value:1},{name:'name2',value:2}];
var json=[];
for(var i=0;i<post.length;i++)
{
var temp={};
temp[post[i].name]=post[i].value;
json.push(temp);
}
var stringJson = JSON.stringify(json);
alert(stringJson );
http://jsfiddle.net/3mYux/
You have extra comma in your JSON string. JSON string format: {"JSON": "Hello, World"}
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
// remove last comma:
edited = edited.substring(0, edited.length-1) + "}";
Can't you just build up a hash and do toString on the hash? Something like this:
var edited = {};
for(var i=0;i<POST.length-1;i++) {
edited[POST[i].name] = POST[i].value;
}
Or maybe JSON.stringify is what you are looking for: http://www.json.org/js.html

Categories

Resources