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))
}
Related
This is my code. I am trying since a couple of days to create an Array of Objects, which I will then store in Local Storage. Here is the problem, I need to first Get the existing value from Local Storage.
I then need to add the new data object to the existing array. I then convert it into JSON so that I can store it back in the local storage.
onRegisterSubmit(){
const user = {
a: this.a,
b: this.b,
c: this.c,
id: Date.now()
}
var abc = [];
var get = JSON.parse(localStorage.getItem('user'));
abc = [get];
abc.push(user);
localStorage.setItem('user', JSON.stringify(abc));
console.log(JSON.stringify(abc));
console.log(get);
}
I want the JSON to be an array of objects like this,
[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}]
This is my JSON.
[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]
I've been trying for several days and any help will be greatly appreciated.
The issues with that code are:
You're wrapping the result you get in an array, but in theory, you want to already have an array.
You're storing user, not get or abc. (You removed that with an edit.)
To store the array, do what you're doing:
localStorage.setItem("users", JSON.stringify(users));
To get the array:
users = JSON.parse(localStorage.getItem("users") || "[]");
Note how that provides a default (empty array) if getItem returns null because we've never stored our users there.
To add a user to the array:
users.push({id: 1, foo: "bar"});
Example (live on jsFiddle [Stack Snippets don't allow local storage]):
(function() { // Scoping function to avoid creating globals
// Loading
var users = JSON.parse(localStorage.getItem("users") || "[]");
console.log("# of users: " + users.length);
users.forEach(function(user, index) {
console.log("[" + index + "]: " + user.id);
});
// Modifying
var user = {
id: Math.floor(Math.random() * 1000000)
};
users.push(user);
console.log("Added user #" + user.id);
// Saving
localStorage.setItem("users", JSON.stringify(users));
})();
That shows you the list of current users in the console, adding one each time you refresh the page.
Try something like this:-
link https://jsfiddle.net/sureshraina/nLexkyfw/1/
var mydatas = new Array();
mydatas[0] = "data";
mydatas[1] = "data1";
mydatas[2] = "data2";
localStorage["mydatas"] = JSON.stringify(mydatas);
var datas = JSON.parse(localStorage["mydatas"]);
See this post.
You can't store Objects, you have to store a String. So the workaround is to stringify your Object before you store it (for example, you could use change it to a JSON object, store it, and read it again when needed).
I am trying to retrieve an arrray from local storage, append a new array with the same keys, then stick it back into storage. I can't seem to get it to work however, I've tried turning my arrays into object, and objects into arrays (I'm new to programming so I'm not sure what the best way is.) I've also tried using the spread operator, object.entries(), object.assign() and a few other nonsensical options.
EDIT:
Saved to storage are the user input values:
"[[["name","bob ross"],["about","Painter"]]]"
I want the user to be able to add "Bilbo Baggins" for name, and "Hobbit" for about, then the storage should look like:
"[[["name","bob ross"],["about","Painter"]]], [[["name","Bilbo Baggins"],["about","Hobbit"]]]"
Any help would be greatly appreciated! Here's my code:
//============= Allows writing to LocalStorage without overwrite ==========================
submitbtn.addEventListener('click', function () {
const oldInfo = JSON.parse(localStorage.getItem('data')); // Retrieves info from storage to make it writeable
console.log('old Info: ', oldInfo); // Shows user what's currently saved in oldInfo
const newInfo = {};
newInfo.name = name.value; // Name and about are user input values
newInfo.about = about.value;
let array = Object.entries(newInfo); // Turns newInfo into an array
console.log('new info: ', newInfo);
oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log(oldInfo);
localStorage.setItem('data', JSON.stringify(oldInfo)); // Saves newly updated array to localStorage
});
I advise you to keep an object format, as you seems to only need to update properties, and not store.
That way, you can simply update your store by using your oldInfo object and using spread operator to create a new object from it (and get rid of conversion):
Let's say you put this in your localStorage (stringified):
const initialInfo = {
name: '',
about: ''
};
Then you can simply do
const oldInfo = JSON.parse(localStorage.getItem('data'));
localStorage.setItem(
'data',
JSON.stringify({ ...oldInfo, name: name.value, about: about.value })
);
This ... are syntaxic sugar for Object.assign, and to my mind, helps a lot to read instruction.
Here it means that you are 'cloning' the oldInfo object, and assigning new values to listed properties placed behind it.
EDIT:
After question editing; if you want to store multiple objects within an array, you should go with array spread operator. Like so:
const oldInfo = JSON.parse(localStorage.getItem('data'));
// oldInfo = [{ name: 'example', about: 'test' }];
const yourNewObject = {
value: name.value,
about: about.value
};
localStorage.setItem(
'data',
JSON.stringify([ ...oldInfo, yourNewObject ])
);
This way you will add an object to your array
I've cleaned up the code a little.
Your code should work, except that is was missing some error handling for the first load.
// Mock data
const name = { value: 'Foo name' };
const about = { value: 'Bar about' };
const submitbtn = document.getElementById('submit');
// Fake localStorage to make it work in the snippet
mockLocalStorage = {
getItem: (key) => this[key],
setItem: (key, value) => this[key] = value
};
submitbtn.addEventListener('click', function() {
// Make sure we get -something- back in case this is the first time we're accessing the storage.
const oldInfo = JSON.parse(mockLocalStorage.getItem('data') || '[]');
console.log('Before', oldInfo);
// The creation of the new object can be done in 1 step.
const array = Object.entries({
name: name.value,
about: about.value
});
oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log('After', oldInfo);
mockLocalStorage.setItem('data', JSON.stringify(oldInfo));
});
<button id="submit" type="button">Submit!</button>
what is the easiest way to retrieve form values to send to localStorage as a JSON string? I started a function with a for loop but am stuck..any nudges are greatly appreciated(still very new to this) No JQuery please. Thank you
<input type="submit" name="submit" value="submitOrder" onclick="return getValues();">
var userOrder='';
function getValues(){
for(var i=0; i < document.forms[0].length - 1; i++){
console.log(document.forms[0][i]);
return false;
}
}
localStorage.setItem('userOrder',JSON.stringify(userOrder));
console.log(localStorage.getItem('userOrder'));
You could do it like this:
html:
<form id="myform">
<input type="text" name="test">
<input type="submit" value="submitOrder">
</form>
js:
const userOrder = {};
function getValues(e) {
// turn form elements object into an array
const elements = Array.prototype.slice.call(e.target.elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if (el.type !== "submit") {
userOrder[el.name] = el.value;
}
});
// finally save to localStorage
localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myform").addEventListener("submit", getValues);
No need for jQuery. This uses ES 2015 syntax but if you need to support old browsers just run it through babel.
// Iterate over all the forms in the document as an array,
// the [...stuff] turns the nodelist into a real array
let userdata = [...document.forms].map(form => {
// iterate over all the relevant elements in the form and
// create key/value pairs for the name/object
return [...form.elements].reduce((obj, el) => {
// Every form control should have a name attribute
obj[el.name] = el.value;
return obj;
}, {});
});
// convert the data object to a JSON string and store it
localStorage.setItem('userOrder', JSON.stringify(userdata));
// pull it pack out and parse it back into an object
let data = JSON.parse(localStorage.getItem('userOrder'));
If the forms all have ids (and they should) you could also use reduce in the outer layer instead of map and hash on the form id:
let userdata = [...document.forms].reduce((result, frm) => {
result[frm.id] = [...frm.elements].reduce((obj, el) => {
and so on.
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;
};
I'm trying to loop through a number of items, and create a json object. Each loop should be a new item on the object, but I'm having some issues doing it. It seems that only one set of items gets added, instead of multiple ones.
Here is my code:
jsonObj = {}
rows.each(function (index) {
jsonObj["id"] = $this.find('.elementOne').val();
jsonObj["name"] = $this.find('.elementTwo').text();
});
Here is what my json looks like:
{
id: "3"
name: "Stuff"
},
Here is what I am trying to do:
{
id: "1"
name: "Stuff"
},
{
id: "2"
name: "Stuff"
},
{
id: "3"
name: "Stuff"
}
There is no JSON here. Please don't confuse:
A JavaScript object (a data structure)
A JavaScript object literal (code to create such a data structure)
JSON (a data format based on a subset of object literal notation)
If you want an ordered list of objects (or any other kind of JavaScript data structure) then use an array. Arrays have a push method.
var myData = [];
rows.each(function (index) {
var obj = {
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
};
myData.push(obj);
});
You override the object instead of adding it a new value each iteration.
Fixed code using an array:
jsonObj = [];
rows.each(function(index) {
jsonObj.push({
'id': $this.find('.elementOne').val(),
'name': $this.find('.elementTwo').text()
});
});
What you want is an array of objects. When you try to write the same property on the same object multiple times, it gets overwritten which is why you're seeing id and name contain values for the last iteration of the loop.
Although you haven't tagged the question with jQuery, it does look like jQuery, so here's a solution:
I've taken the liberty to change $this to this because $this seems to be referring to the same object in each iteration, which is now what you may want (methinks)
var myArray = rows.map(function() {
return {
id: $(this).find('.elementOne').val(),
name: $(this).find('.elementTwo').text()
};
});
You can do it like this with jquery. The function will expect form elements of type input. It will iterate over thr passed form and it will collect each input name and value and it will create a json object like
Exmple:
HTML
<form action="" method="post" id="myForm">
<input type="text" name="field1" value="I am value of field 1"/>
<input type="text" name="field2" value="I am value of field 2"/>
</form>
Javascript
function buildObject(form) {
var jsonObject = [],
tempObj = {};
$(form).find("input:not(input[type='submit'])").each(function() {
tempObj[$(this).attr("name")] = $(this).val();
});
jsonObject.push(tempObj);
return jsonObject[0];
}
buildObject($("#myForm"));
//Will produce
jsonObj = {
field1 : "I am value of field 1",
field2 : "I am value of field 2"
}
This is because you're merely overwriting the same properties of your object, id and name, each time. You need to be making a sub-object for each, then push it into the master object (which I've converted to array, since it's non-associative).
var jsonObj = []
rows.each(function (index) {
var temp_obj = {};
temp_obj["id"] = $this.find('.elementOne').val();
temp_obj["name"] = $this.find('.elementTwo').text();
jsonObj.push(temp_obj);
});
[EDIT] - as Mark Eirich's answer shows, the temp_obj is unnecessary - you could push an anonymous object instead, but I defined temp_obj just to make it crystal clear what's happening.
Also read Quentin's very good points re: common confusion between JavaScript objects and JSON.
var jsonObj = [];
rows.each(function(index) {
jsonObj.push({
id: $this.find('.elementOne').val(),
name: $this.find('.elementTwo').text()
});
});