Print json object from local storage - javascript

i need to print an array of json object which are been entered by user through text box, this function is executed by button click. i need to store all the string localy that are entered by the user in text box. and display it in my console in this formate [{"aaa"},{"bbb"},{"ccc"}]
<!DOCTYPE html>
<html>
<body>
Enter the string :
<input type="text" id="names">
<button onclick="myFunction()"> Click Me</button>
<script>
function myFunction(){
var myNames = new Array();
myNames = document.getElementById("names").value;
this.names = myNames;
localStorage["myNames"] = JSON.stringify(myNames);
console.log(JSON.stringify(myNames));
var name = JSON.parse(localStorage["myNames"]);
console.log(name);
};
</script>
</body>
</html>
Currently this code just print the data like this "aaa", if i add another data bbb, only the 2nd data "bbb"is displayed. i want all the data to be viewed in this formate [{"aaa"},{"bbb"},{"ccc"}] or even like this [{"name":"aaa"},{"name":"bbb"},{"name":"ccc"}] .
Could someone help me?

That's not related to localStorage or JSON.
When you perform myNames = document.getElementById("names").value; you replace the empty Array with a string.
You may use .push on array : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push
And create an object then pushing it, for example myObj = {'v': value}; myArray.push(myObj);

you can try this:
var myNames = []
function myFunction(){
var oldItems = JSON.parse(localStorage.getItem('myNames')) || [];
newItem = {"name":document.getElementById("names").value};
oldItems.push(newItem);
localStorage.setItem("myNames", JSON.stringify(oldItems));
console.log(JSON.parse(localStorage.getItem("myNames")));
};

If you want to preserve the previously entered data, you have to retrieve them first and alter them.
Below are two functions; one that adds an item to the array. If the array isn't present yet (so no data has been entered previously), it creates a new array for you.
Afterwards it stores the data in the localStorage again.
Upon entering new data that needs to be added, it first retrieves any previous entries and alters that. Then it stores again and so on and so on.
function myFunction(){
var myNames = localStorage.getItem('myNames'),
parsedArray = JSON.parse(myNames),
valueToAdd = document.getElementById("names").value;
// Add the new item to the original array.
parsedArray = addToArray(parsedArray, valueToAdd);
localStorage.setItem('myNames', JSON.stringify(parsedArray));
console.log(parsedArray);
};
function addToArray (array, item) {
// If the array doesn't exist, create one
if (!array) {
array = [];
}
// Add the item to the array.
array.push(item);
return array;
};

Related

store array into localstorage instead of replace

I'm using local storage as below like
var post = {
title: 'abc',
price: 'USD5'
};
window.localStorage['book'] = JSON.stringify(post);
I want to create nested json in my localstorage, if above code is within a click event for the user to click save, it will delete the old data and replace it. How to push new value as an array object?
Use an actual array, e.g. on page load:
var posts = JSON.parse(localStorage['book'] || "[]");
Then as you're working with it, add to the array in memory:
posts.push({
title: 'abc',
price: 'USD5'
});
Any time you want to save the value back to local storage:
localStorage['book'] = JSON.stringify(posts);
Here's a complete functional example (live copy; sadly, Stack Snippets disallow local storage):
HTML:
<div>
<label>
Name:
<input type="text" id="txt-name">
</label>
</div>
<div>
<label>
Price:
<input type="text" id="txt-price">
</label>
</div>
<div>
<input type="button" value="Add" id="btn-add">
</div>
<div id="list"></div>
JavaScript (must be after the HTML in the document):
(function() {
var nameField = document.getElementById("txt-name"),
priceField = document.getElementById("txt-price");
// On page load, get the current set or a blank array
var list = JSON.parse(localStorage.getItem("list") || "[]");
// Show the entries
list.forEach(showItem);
// "Add" button handler
document.getElementById("btn-add").addEventListener(
"click",
function() {
// Get the name and price
var item = {
name: nameField.value,
price: priceField.value
};
// Add to the list
list.push(item);
// Display it
showItem(item);
// Update local storage
localStorage.setItem("list", JSON.stringify(list));
},
false
);
// Function for showing an item
function showItem(item) {
var div = document.createElement('div');
div.innerHTML =
"Name: " + escapeHTML(item.name) +
", price: " + escapeHTML(item.price);
document.getElementById("list").appendChild(div);
}
// Function for escaping HTML in the string
function escapeHTML(str) {
return str.replace(/&/g, "&").replace(/</g, "<");
}
})();
Side note: If there's any chance at all you might have to support your code on older browsers that don't have local storage at some point, you can give yourself the option of using a polyfill that writes to cookies if you use the more verbose .getItem(...)/.setItem(..., ...) API, as they can be polyfilled whereas accessing via [] as in the above can't be.
localStorage supports strings. You should use JSONs stringify() and parse() methods.
If I understood the question and what you are looking for is storing an array and not just an object with properties.
As scunliffe commented, What you can do in order to add items to an array which is stored in the local storage is:
Generating the array with first object:
var array = [];
array[0] = //Whatever;
localStorage["array"] = JSON.stringify(array);
Adding items to the array:
//Adding new object
var storedArray = JSON.parse(localStorage["array"]);
sotreadArray.push(//Whatever);
localStorage["array"] = JSON.stringify(array);
This way you store an JSON object representing an array.
As mentioned in this post
You can also extend the default storage-objects to handle arrays and objects by:
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}

How can I parse a JSON object containing a colon

I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)

How to take data from Ext.Record?

I can take record from store: var record = store.getAt(i);
But if i want to take fileds which have a same name from record i get only first field value. For example if i have XML with:
Code:
<zem>
<parcel>
....
<parcel>
<really>
<price>555.555<price>
</really>
<really>
<price>666.666<price>
</really>
</zem>
And using record.get("price") i can get only 555.555 value.
Its possible to get values of all fields of <really>? Or array of values of all fields with name=<price>?
Take a walk on store:
var res = [];
store.each(function(record) { res.push(record.get('price')); })

Displaying information from a multidimensional array?

I have new inputs for a multidimensional array. The original inputs that are already defined are displayed correctly when called upon but the new inputs write as "undefined". I think it is recognizing the new inputs as variables. How do you get them to show up as a string?
var original = new Array(); //this is the array
function input(title, artist, ddate, genre, picsrc) {
this.Title = title;
this.Artist = artist;
this.Ddate = parseInt(parseFloat(ddate));
this.Genre = genre;
this.Picsrc = picsrc;
}
original[0] = {title:"Hope II", artist:"Gustav Klimt", ddate:1907, genre:"Art Nouveau", picsrc:"gustav.jpg"}; //and so on
Values that are added to the array are taken from a form.
function addit(form) {
G = form.Title.value //as a test
original[original.length++] = new input(form.Title.value, form.Artist.value, form.Ddate.value, form.Genre.value, form.Picsrc.value)
alert("your entry has been added")
alert(G) //value shows up in the alert
}
but when it is called back in this function:
$("#info").html(original[currentrecord]["title"]+"<br /><h2>"+original[currentrecord]["artist"]+"</h2>"+original[currentrecord]["ddate"]+"<br />"+original[currentrecord]["genre"]);
everything is being written as "undefined".
I am assuming that the data is successfully being added to the array, but maybe not in the right format?
I prefer using dot notation, but it's not a requirement.
The real issue is: JavaScript is case sensetive.
I would do it like this:
original[currentrecord].Title
original[currentrecord].Artist
and so on...
At one place in your code you are using all lowercase (when initializing original[0]), but in the constructor function you are using uppercase for the first letter.

Creating a key/pair object using jQuery and some inputs

I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.
Here is the javascript code I have so far:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[type='hidden']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.addKey(productKey, productQuantity); ?
});
// 1. Grab the values of each ammount input and it's productId.
// 2. Send this dictionary of key pairs to a JSON action method.
// 3. If results are OK, reload this page.
});
</script>
The comments I wrote are just guidelines for me on how to proceed.
Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.
I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.
items[productKey] = productQuantity;
In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:
var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"
So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:
items[productKey] = productQuantity;
items[productKey]; // => productQuantity
You can add anonymous objects to the items array like:
items.push({
key: productKey,
quantity: productQuantity
});
Then access them later as items[0].key or items[0].quantity.
Also you can use JQuery.data method and like that you can also get rid of those hidden.

Categories