I have an initial array (users) with multiple (string and numeric) arrays therein:
var users = [
['User: 10792 - Jack',45.7546,-117.807,2,'/res/smR11.gif'], ['User: 11248 - John',38.0867,131.976,3,'/res/smR08.gif']
];
I have a string of data from our server in the current form of:
newData = "['User: 18469 - Gary',-33.9399732539481,151.164383805489,3,'/res/markerw.gif'],['User: 10020 - Robert',40.6437563454472,-73.7593346140851,6,'/res/smR10.gif']";
I erase all existing data with users.length = 0;
I then need to insert the newData into the users array.
NOTE: I can obviously modify the server data into any other format
that would be more suitable.
Any help would be greatly appreciated.
try something like this
var users = JSON.parse(newData);
Your newData string looks very similar to the javascript above it. How about this...
users = eval('[' + newData + ']');
[EDIT]
As Bergi, rajeshkakawat and StephenJames pointed out, eval will work but is less secure.
See: JSON.parse vs. eval()
Related
I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem
I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}
I have an array like this:
var people = [
'<option value=\'64\'>Tom',
'<option value=\'76\'>Dan',
];
I am looping through each item in the array to extract the value (like the number 64 in the first item) and the text (like Tom in the first item). I tried multiple ways of extracting these details from each item but I am unable to. I even tried using substrings and other methods. Can someone tell me how to extract this information?
You should use a regular expression in such a case.
For example:
var things = people.map(function(s){
return s.match(/(\d+)\W+(\w+)$/).slice(1)
});
This builds this array:
[ ["64", "Tom"], ["76", "Dan"] ]
You might want to adapt it for your precise needs:
check an array is returned by match, if some strings might be invalid
change the regex if the pattern is more variable
Note that you probably shouldn't have such an array to start with. If you generate it server-side, you should opt for the generation of a JSON structure instead and let the client script build the interface from the data, instead of building it from something which is neither clean data nor GUI.
You can use multiple split :
var str = '<option value=\'64\'>Tom';
var tmpStr = str.split("'");
var number = (tmpStr[1].split("\\"))[0];
var name = (tmpStr[2].split(">"))[1];
document.write(number + " " + name);
I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.
In particular, I need the address, postcode, region, and locality.
This JSON array is being stored as a JS var called "data"
Does anyone know how I can begin parsing out those things? Thank you all!
[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and
Dining","Restaurants"]],"country":"us","email":"kimd#thedussingroup.com","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]
Appreciate the help!
You JSON is an array (since it's contained in [ and ]), so you need:
var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
postcode = data[0].postcode;
and so on...
for(var i in data[0]){
window[i] = data[0][i];
}
alert(address);
You can do this using JSON.parse
var data= your json;
JSON.parse(data);
Update:
In your case you don'e even need to parse you can use directly like
console.log(data[0].address); //returns 2801 Elliott Ave
console.log(data[0].category_ids); //returns [347]
Check this JSFiddle
I have a cookie that stores 5 values separated by commas in one cookie. I'm able to retrieve the value of ExampleCookie as follows (as example):
var CookieValue = readCookie('ExampleCookie');
//returns Foo,Bar,Foo1,FooFighter,Bar2
How do I parse through CookieValue to assign individual variables such that I can assign a variable to each of the 5 parts?
I've found ways to do this with PHP but not javascript.
Thanks in advance for any advice.
use the String.split(delimiter) method
var array = readCookie('ExCook').split(",");
Reference:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
You need to make an array from string:
CookieParams = CookieValue.split(",");
CookieParams[0] = Foo
CookieParams[1] = Bar
You could split the CookieValue into individual values in an array via the the split() method.
var valList = CookieValue.split(','); // ["Foo", "Bar", "Foo1", "FooFighter", "Bar2"]
If you then want the values to be assigned to individual variables, you would need to loop through the array and manually make the assignment.
JSON.stringify, and JSON.parse are your best cleanest bets (imho)
var values = JSON.parse(readCookie('ExampleCookie'));
createCookie('ExampleCookie',JSON.stringify(values));
This has the added benefit of being able to set key values in your object/array.
Assuming you're using the functions found at quirks mode just ensure your cookie values stringified don't go over the 4000 char limit found in most browsers.
I quickly realized this was more of a question on Split than about cookies. Here is what i came up w/.
var splits = ExampleCookie.split(",");
var slot1 = splits[0];
var slot2 = splits[1];
var slot3 = splits[2]; etc.