localStorage Array split - javascript

I have a script to put formdata into localStorage. The data saved in an array. I want that the elements in the array where list without brackets and underneath eachother. Does somebody have a hint for me how to do that?
The array and the output in the div looks like this:
[[{"EMail":"testmail#test.com","Salutaion":"Mr","FirstName":"Test","Name":"Testname"},{"EMail":"testy#test.com","Salutaion":"Mrs","FirstName":"Testy","Name":"TestyFemale"}]]
The script to show the array in a div:
var output = '';
for (var key in localStorage) {
output = output+(key + ':' +localStorage[key])+'\n';
}
$('#divtoshowarray').html(output);
https://jsfiddle.net/6x490kot/

Here is the updated code
$(document).ready(function() {
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var output = '';
var objectFromLS = JSON.parse(localStorage.getItem('testObject'));
for (var key in objectFromLS) {
if (objectFromLS.hasOwnProperty(key)) {
output = output+(key + ':<br>' +objectFromLS[key])+'\n';
}
}
$('#divtoshowarray').html(output);
});
Key Points
You want to iterate on testObject data stored in localStorage. So you need to get testObject from localStorage and iterate on it. Please note, localStorage.getItem will return string, so, you need to parse it so as to return a JSON.
Then you need to iterate on the object, to paint key value pair.
For reference - https://jsfiddle.net/6x490kot/1/

Related

How to create dynamic object attributes from Ajax response in Javascript

I'm using Ajax in order to get a list of items of an inventory, I would like to have an object named inventory and then create attributes named as the items of the response, so that means if I insert more items in my database I wouldn't need to hard code the elements of the object in my javascript file. Right now I'm able to create the object, but I can't access de dynamically created attributes and their values. I would like to alter the values with some user Input like pressing a button.
I've tried to use a Dictionary and searched but that didn't seem to work
var inventory = {};
$.ajax({
url:"phpf/getItems.php",
type:"POST",
data:{},
success: function (data) {
var result = JSON.parse(data);
for (var index = 0; index < result.length; index++) {
var str = String(result[index][0]);
inventory[str] = 5;
}
}
});
console.log(inventory["Cookies"]);
console.log(inventory[0]);
I would like to access the information of the object like inventory["something"] but console says it's undefined, and when I try to add the value to another number it says NAN as result
You can already access your data parsed from your JSON.parse, it returns an object so it can be called using the ['key'] accessor :
let json = '{"key1": 2, "key2": "test"}';
let values = JSON.parse(json);
console.log(values.key1);
console.log(values['key2']);
Inventory is an object, so you want to access keys and values in your object using dot notation.
let inventory =
{
item1: "Cookie",
item2: "Cake"
}
inventory.item3 = "Brownies";
console.log(inventory.item1);
console.log(inventory.item2);
console.log(inventory.item3);
Also to loop through an object you want to go like so:
for (var key in object) {
//your code here
}

How do I update my array with my object's value? [duplicate]

This question already has answers here:
How do I update specific key value of the local storage array?
(4 answers)
How to store and update a localStorage key object which has properties of different data types?
(1 answer)
Closed 4 years ago.
myObj is storing the input coming from the user which is pushed to arr which is store in localStorage as a 'data' key. On submit, I want the new values to be added to arr and not overwrite it (in the else part). The following code works but overwrites the old data:
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const arr = new Array()
if (window.localStorage.length == 0) {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
} else {
const arr = JSON.stringify(myObj);
window.localStorage.setItem('data', arr);
}
One thing to note is that JSON.stringify returns a string, not an array -- and, conveniently, localStorage stores key/value pairs where the value is a string, so this all works as it's supposed to.
To update the value in localStorage, you could first retrieve it, then modify it however you like, and then store it again. Since you're working with javascript objects, you'll need to use JSON.parse and JSON.stringify to convert back and forth between objects (to work with) and strings (to store).
This pattern looks like:
let retrievedString = localStorage.getItem('data');
let retrievedObject = JSON.parse(retrievedString); // convert string to obj
let oldColor = retrievedObject.field7; // we don't actually use oldColor
let newColor = "#666666";
retrievedObject.field7 = newColor; //change existing property
retrievedObject.field99 = "99"; // add new property
let modifiedString = JSON.stringify(retrievedObject); // ready to store new version
localStorage.setItem('data', modifiedString);
I added more to the code sample to clarify the kinds of things you can do with your retrieved object before converting back to a string and finally replacing the old version in storage.
Your mistakes:
arr, despite its name, isn't an array.
you never recover the saved data
Check the code below to see my take on the problem: (before trying it, you should erase your localStorage)
var myObj = {
field1: fname.value,
field2: lname.value,
field3: birth.value,
field4: salary.value,
field5: String(selectedGender),
field6: String(choicesOfHobby),
field7: color.value,
field8: String(choicesCountry),
field9: textArea.value
}
const array = window.localStorage.data || []; // get your saved array, or create a new one
array.push(myObj); // Add the current item to the array
window.localStorage.setItem('data', JSON.stringify(array)); // save it again
Any further question please just ask
You need to use something like this:
let data = localStorage.getItem('data');
let dataObj = JSON.parse(data);
dataObj[fieldKey] = fieldObj;
localStorage.setItem('data', JSON.stringify(dataObj));
Firstly read localstorage documents how to use it: https://developer.mozilla.org/tr/docs/Web/API/Window/localStorage
You have to push data array to localstorage and push your objects to your data array after getting data array from localstorage. Finally don't forget to set your data array to localstorage again. Your localstorage part code should be like below:
var data = JSON.parse(window.localStorage.getItem("data"));
if(data === null){
data = [];
}
data.push(myObj);
window.localStorage.setItem("data",JSON.stringfy(data));
You just need to use this:
arrInStorage = localStorage.getItem('data') || [];
arr = JSON.parse(arrInStorage);
arr.push(myObj);
localStorage.setItem('data', JSON.stringify(arr));
instead of your if / else statement.

Parse Javascript output array / Parse URL Hash

I'm trying to parse out a single value from a URL String with three varaibles, and I am currently using the code:
var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);
for (var i = 0; i < hash_array.length; i++) {
hash_key_val[i] = hash_array[i].split('=');
var array = hash_key_val[i];
console.log(array);
}
This code works to parse out the hash, but it creates separate arrays for each item and value like so:
["object1", "value1"]
["object2", "value2"]
["object3", "value3"]
By altering the array to var x = JSON.stringify(array[1]);
I can get the value which is all I need, but I only need the first value, while this code still returns:
"value1"
"value2"
"value3"
How can I alter the code so that the function only outputs value1?
Thanks!
Change the 1 for 0; Arrays start at zero index. Also I am not sure if you are aware that you are looping over the values as you are printing them out.
var arr = [
["object1", "value1"],
["object2", "value2"],
["object3", "value3"]
];
console.log(arr[0][1]);
As Arrow mentioned you need to change the index at which you access array from 1 to 0.
Additionally, why not use map:
var keys = hash_array.map(function(param){
return JSON.stringify(param.split('=')[0]);
}
with keys being ["object1", "object2", "object3"]

Convert array of javascript objects to JSON

I have a set of data in the format:
[{"title":movietitle1, "id":445, "release":"16JUN1985"}, {"title":movietitle2, "id":487, "release":"12AUG1993"}]
Which I need to convert into JSON formatted as such:
{
"movietitle1":{"id":445,"release":"16JUN1985"},
"movietitle2":{"id":487, "release":"12AUG1993"}
}
I don't have any idea of how to make this happen.
You can do this with JSON.stringify() and some basic data manipulation.
Store your data in a variable, lets call it input_data.
Loop through your data and use each entry to build up another variable, lets call it output_data.
// create an object to store the newly formatted data
var output_data = {};
// the code in here is run once for each item in input_data
for (var i = 0; i < input_data.length; i++) {
// get the current item's title
var title = input_data[i].title;
// use the title as the key in the output data
// and assign the other values to that key
output_data[title] = {
id: input_data[i].id,
release: input_data[i].release
};
}
// use JSON.stringify() to make a valid JSON string
var json = JSON.stringify(output_data);
// now use the variable json which contains your JSON string
What you are asking for is to turn an array into a map , keying by a specific property, If you really want JSON, you can just call JSON.stringify on the resulting JS object.
http://jsfiddle.net/FfE8f/1/
/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* #param {object[]} list of objects to be transformed into a keyed object
* #param {string} keyByProp The name of the property to key by
* #return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};
console.log(mapFromArray([
{"title": "title 1", "id":445, "release":"16JUN1985"},
{"title":"movietitle2", "id":487, "release":"12AUG1993"}],
"title"
)));
// outputs
{
"title 1": {"title":"title 1","id":445,"release":"16JUN1985"},
"movietitle2": {"title":"movietitle2","id":487,"release":"12AUG1993"}
}
See More efficient way to search an array of javascript objects?
Your mixing terms. I'm assuming you're asking about manipulating data with JavaScript objects and not strings with JSON data. (The later can be converted with JSON.parse).
First iterate over the array and assigning to an object. This kind of data manipulation works well using Underscore, check it out.
In vanilla JS lets try something like this:
var newData = {};
data.forEach(function(item) {
var title = item.title;
delete item.title;
newData[title] = item;
});
A little crufty but gets the job done.
Personally I'd use this Underscore version:
var newData = _(data).chain()
.map(function(item) {
return [item.title, _(item).omit('title')];
})
.object()
.value();

How to set hash key dynamically in javascript

With this code,
h = {}
for (var i in [0,1]){ h[i.ToString] = i; }
I expected same result with h["1"] = 1 and h["2"] = 2.
Why is this code doesn't work, and how can I define hash key dynamically in javascript?
The for .. in loop in JS iterates over keys, not over values (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).
So in your case, you iterate over the keys of the array you have in there.
Those will be 0, 1, 2 ... no matter what you put in there.
What you could do instead would be something like this:
var obj = {};
var data = [1,2,3,4];
data.forEach(function(val) {
obj[val] = val;
});

Categories

Resources