Javascript localstorage get the value into array one by one - javascript

Problem:
I would like get the localstorage value "car", i want to get the result like car = ["red","blue"] in other page, i want to get the result into array one by one. How can i fix it?
page 1:
car = ["red","blue"];
localStorage.setItem("car", JSON.stringify(car));
Another Page:
var car1 = JSON.parse(localStorage.getItem("car"));
alert(car1[0])
****show two record at the same time , i want to put it into array like car1[0] = red; car1[1] = blue;

as i know, when you convert it to json it wouldn't parse to you items like array
so car[0] doesn't work as you want,
This is a good resource of using localstorage:
https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/
U must enter the items as an object and give them an id
like this:
{
name: red,
id: 1,
}
Then retrieve it by car id.
and a better answer: How do I store an array in localStorage?
And know it JSON is not supported in IE7 and earlier.

Related

how to access key/value pairs from json() object?

I'm calling an external service and I get the returned domain object like this:
var domainObject = responseObject.json();
This converts the response object into a js object. I can then easily access a property on this object like this
var users = domainObject.Users
Users is a collection of key/value pairs like this:
1: "Bob Smith"
2: "Jane Doe"
3: "Bill Jones"
But CDT shows users as Object type and users[0] returns undefined. So how can I get a handle to the first item in the collection? I'm assuming that some type of type cast is needed but not sure how I should go about doing this
UPDATE
Here is one way I could access the values:
//get first user key
Object.keys(responseObject.json().Users)[0]
//get first user value
Object.values(responseObject.json().Users)[0]
But I need to databind through ng2 so I was hoping for a simpler way like this:
<div>
<div *ngFor="let user of users">
User Name: {{user.value}}
<br>
</div>
</div>
Maybe I should just create a conversion function in my ng2 component which converts the object into what I need before setting the databinding variable?
UPDATED ANSWER
So after scouring through a few docs I found the "newish" Object.entries() javascript function. You can read about it here. Pretty cool.
Anyways, give this a try. I am ashamed to say that I don't have time to test it, but it should get you going in the right direction.
usersArray = []
// Turn Users object into array of [key, value] sub arrays.
userPairs = Object.entries(users);
// Add the users back into an array in the original order.
for (i=0; i < userPairs; i++) {
usersArray.push(_.find(userPairs, function(userPair) { return userPair[0] == i }))
}
ORIGINAL ANSWER
I would use either underscore.js or lodash to do this. Both are super helpful libraries in terms of dealing with data structures and keeping code to a minimum. I would personally use the _.values function in lodash. Read more about it here.. Then you could use users[0] to retrieve the first item.
The only caveat to this is that lodash doesn't guarantee the iteration sequence will be the same as it is when the object is passed in.
users = _.values(users);
console.log(users[0]);
How about this:
let user= this.users.find(() => true)
This should return the "first" one.
If your initial object is just a plain object, how do you know it is sorted. Property members are not sorted, ie: looping order is nor guaranteed. I´d extract the user names into an array and the sort that array by the second word. This should work (as long as surnames are the second word, and only single spaces are used as separators).
var l=[];
for(var x in users) {
push.l(users[x]);
}
var l1=l.sort ( (a,b) => return a.split(" ")[1]<b.split(" ")[1]);

JQuery Mobile JSON Stringify

I'm new in jquery mobile. I'm doing a shopping list application for my school assignment and I'm requested to store objects in local storage.
Each item must include the following information: item Name, item quantity and a Boolean is_bought.
I wish to store all items data into one JSON string. Items data is entered by user from an other page.
My problem is
1)How items can be stored in local storage through JSON stringify.
2)How items data can be retrieved from JSON string to be represented into a list.
First: If I understood you right you have an object(json) structure like:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
If not (in question you have no key(name) for your variables) your structure must be like I showed for having an access to each variable in the object.
Second: About localStorage. It is limited to handle only string key/value pairs, so you can't just save an object in it. You have to use JSON.stringify() to parse your object into the string and save in localStorage, then, after retrieving, use JSON.parse() to parse it back. The code could look like this:
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT: TO STORE MULTIPLE ITEMS
So, if your question is about storing multiple items and distinguishing them, and if your item's name is unique and you know what item is bought, you can store them into the localStorage with the key of item's name, e.g.
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));

Javascript object/array manipulation

Struggling with some javascript array manipulation/updating. Hope someone could help.
I have an array:
array('saved_designs'=array());
Javascript JSON version:
{"saved_design":{}}
I will be adding a label, and associated array data:
array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))
Javascript version:
{"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
I want to be able to append/modify this array. If 'label' already defined...then cycle through the sub data for that element...and update. If 'label' doesnt exist..then append a new data set to the 'saved_designs' array element.
So, if label is not defined, add the following to the 'saved_designs' element:
array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')
Things arent quite working out as i expect. Im unsure of the javascript notation of [], and {} and the differences.
Probably going to need to discuss this as answers are provided....but heres some code i have at the moment to achive this:
//saveLabel = label the user chose for this "design"
if(isUnique == 0){//update
//ask user if want to overwrite design styles for the specified html element
if (confirm("Their is already a design with that label ("+saveLabel+"). Overwrite this designs data for the given element/styles?")) {
currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
//edit other subdata here...
}
}else{//create new
var newDesign = [];
newDesign[saveLabel] = [];
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
}
jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));
thanks in advance. Hope this is clear. Ill update accordingly based on questions and comments.
Shaun
It can be a bit confusing. JavaScript objects look a lot like a map or a dictionary from other languages. You can iterate over them and access their properties with object['property_name'].
Thus the difference between a property and a string index doesn't really exist. That looks like php you are creating. It's called an array there, but the fact that you are identifying values by a string means it is going to be serialized into an object in javascript.
var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
thing.saved_designs.label is the same thing as thing["saved_designs"]["label"].
In javascript an array is a list that can only be accessed by integer indices. Arrays don't have explicit keys and can be defined:
var stuff = ['label', 24, anObject]
So you see the error you are getting about 'push not defined' is because you aren't working on an array as far as javascript is concerned.
currentDesigns["saved_designs"] == currentDesigns.saved_designs
When you have an object, and you want a new key/value pair (i.e. property) you don't need a special function to add. Just define the key and the value:
**currentDesigns.saved_designs['key'] = newDesign;**
If you have a different label for every design (which is what it looks like) key is that label (a string).
Also when you were defining the new design this is what javascript interprets:
var newDesign = [];
newDesign is an array. It has n number of elements accessed by integers indices.
newDesign[saveLabel] = [];
Since newDesign is a an array saveLabel should be an numerical index. The value for that index is another array.
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
Here explicitly you show that you are trying to use an array as objects. Arrays do not support ['string_key']
This might very well 'work' but only because in javascript arrays are objects and there is no rule that says you can't add properties to objects at will. However all these [] are not helping you at all.
var newDesign = {label: "the label", class: saveClass};
is probably what you are looking for.

Convert One field in an Object Array data with angularjs and Javascript to another value

In an angularjs controller I have this code:
var ysshControllers = angular.module('theControllers', []);
ysshControllers.controller('CommonController',
function($scope, $http, $route) {
$scope.dbKey = $route.current.customInput;
$scope.urlToDb = 'https://' + $scope.dbKey + '/.json';
$http.get($scope.urlToDb).success(function(data) {
var values = [];
for (var name in data) {
values.push(data[name]);
}
$scope.Items = values;
});
// Initially order by date and time
$scope.orderProp = 'ac';
}
);
It creates an object array with the name Items. The key values are just labed aa, ab, ac etc. When the user inputs data from a drop down menu, I want to save only values like: 1,2,3,4,5 and then when the data is imported back into the website, convert the values back. Like 0 = Bad; 5 = Very Good. So, for every record with the key name ae I want to convert the values from 1,2,3,4,5 to Bad, Okay, Fair, Good, Very Good.
I can figure out the program flow, what I need to know is how to reference the values using object oriented JavaScript I guess.
The data is structured like this:
C5_200630_Option 1
aa:"Option 1"
ab:"Toyota"
ac:6499
ad:"Truck"
ae:"Tacoma, Silver, 1/2 ton 4wd"
af:4
I ran this like of code:
alert(Object.keys($scope.UsedItems));
And it gives values of 0,1,2,3,4 etc. So I guess the key values in $scope.UsedItems are just numbers. I don't know how to access the key and value data specifically. What is a simple way I can just display in an alert what the content of the array is?
I used this line:
alert(data[name].ad);
And that will reference the data in every record with the name ad. So that gives me a way to identify a specific item in the record.
Okay, I figured out a solution:
if (data[name].af === "3") {
data[name].af = "Awesome!";
}
Even though I figured out the solution to my problem, I still have almost no idea what I'm doing. So if there is a better way, let me know.
You can define an array like this
var example = ["Bad", "Not Bad", "Fine", "Good", "Very Good"];
and instead of checking value of data[name].af every time you can simply set it like this
data[name].af = example[data[name].af];
which gives you the result you want as you want data[name].af=3 should be fine and example[3] is what you want...

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources