Setting a empty localStorage object results in "[object Object]" - javascript

I'm trying to save some data to localStorage within a containing object. If I were just using javascript variables, I would do this:
var obj = obj || {};
obj.fname = 'bob';
console.log(obj.fname) // => "bob"
However trying to do this in localStorage
window.localStorage.obj = window.localStorage.obj || {}
window.localStorage.obj.fname = 'bob';
console.log(window.localStorage.obj.fname) // => "[object Object]"
Why won't this same technique work for localStorage? Is there a way to do this?

You have to stringify the object and store it in localstorage.
Then when you need it you have to JSON.parse the json string.
var obj = {
b : 2
};
window.localStorage.obj = JSON.Stringify(obj);
var returnObj = JSON.parse(window.localStorage.obj);

localStorage can store only plain string so you need to
window.localStorage.obj = JSON.stringify({fname: 'bob});
Then for reading you need to parse it back so
var obj = JSON.parse(window.localStorage.obj);
console.log(obj.fname);

As mentioned in this answer everything is stored in the localstorage in string format. Hence, in your case the toString method is being called on your obj before it is set. Setting completing objects in the localstorage under some key should be avoid. Try setting the value bob under a key fname in the localstorage using localstorage.setItem('fname', 'bob') or call JSON.stringify on {fname: 'bob'} before setting it in the obj key in the localstorage

Related

Access to properties of JSON in Node JS

I'm trying to access the age but I cannot, how can I do that?
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(JSON.stringify(json));
This doesn't work for me, obj.carlos is undefined
console.log("Age of Carlos: ", obj.carlos.data.age);
The problem here is the unnecessary call to JSON.stringify, that method is used to convert JavaScript objects to JSON, but has nothing to do with deserializing them.
The code that you need is just this:
var obj = JSON.parse(json);
No need to JSON.stringify. You just only need to parse your values as they are already a JSON string. Here you go:
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);
console.log("Age: ", obj.carlos.data.age);
the problem here is the unnecessary call to JSON.parse(JSON.stringify(json)) conver javascript object to JSON like: JSON.parse(json)
example :
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(JSON.stringify(json));
console.log("Phone of Carlos: ", obj.carlos.data.phone);
You cannot use JSON.stringify() here, because this method converts a JavaScript object or value to a JSON string and you already got a JSON string.
So your code should look like this:
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);

how to turn a string into a variable

Im trying to use a command for a chat program and i want to edit a variable with a command like !editvar variablehere value
so if it variablehere = '123' i want to turn '123' into just 123 or something like 'hello' into hello, in simple words im trying to make a string from a chat message into a variable name
ive tried parsing and string.raw and none worked
if(message.startsWith('keyeditvar')) {
console.log(message)
var bananasplit = message.split(' ');
var bananasplitted = json.parse(bananasplit)
console.log(bananasplitted[0].keyeditvar)
var variable = bananasplit[1]
console.log(variable)
var value = bananasplit[2]
console.log(value)
var variable2 = String.raw(variable)
console.log(variable2)
var value2 = String.raw(value)
console.log(value2)
}
i expected it to work ig
im trying to turn a string into a variable name
In Javascript, you don't usually dynamically define new variables with custom names in the current scope. While you can do it at the global scope, you cannot easily do it in the function or block scope without using tools that are generally not recommended (like eval()).
Instead, you use an object and you create properties on that object. You can use either a regular object and regular properties or you can use a Map object with some additional features.
For a regular object, you can do thing like this:
// define base object
let base = {};
// define two variables that contain variable name and value
let someName = "greeting";
let someValue = "hello";
// store those as a property on our base object
base[someName] = someValue;
console.log(base); // {greeting: "hello"}
Then, you can change the value:
someValue = "goodbye";
base[someName] = someValue;
console.log(base); // {greeting: "goodbye"}
Or, you can add another one:
let someOtherName = "salutation";
let someOtherValue = "Dear Mr. Green";
base[someOtherName] = someOtherValue;
console.log(base); // {greeting: "goodbye", salutation: "Dear Mr. Green"}
console.log(base.greeting) // "goodbye"
console.log(base[someName]); // "goodbye"
console.log(base.salutation) // "Dear Mr. Green"
console.log(Object.keys(base)) // ["greeting", "salutation"]
You can think of the Javascript object as a set of key/value pairs. The "key" is the property name and the value is the value. You can get an array of the keys with:
Object.keys(obj)
You set a key/value pair with:
obj[key] = value;
You get the value for a key with:
console.log(obj[key]);
You remove a key/value pair with:
delete obj[key]
With a plain Javascript object like this, the keys must all be strings (or easily converted to a string).
If you have non-string keys, you can use a Map object as it will take any object or primitive value as a key, but it uses get() and set() methods to set and get key/values rather than the assignment scheme of a plain object.
Please, next time put a clean code...
To convert a string to a number. You can use the function : Number(object)
So for example :
Number('123')
will return 123.
If the object value is not a correct number, it will return NaN.
So for example :
Number('hello')
will return NaN.

Pushing defined variable into javascript object

I am using express.js and the cookie-parser middleware. I am trying to use a function to push the cookie name and the cookie value into an array.
I want the array to end up looking like the following:
loop = [{cookie1: value1}, {cookie2: value2}];
But for some reason when I push the key and the value into the array, the key is just being assigned as a string called key, instead of the actual value set in the function. So my array ends up looking like the following:
loop = [{key: value1}, {key: value2}];
I define the variable 'key' inside the function, and if I console log it inside the function it is set to the right value (i.e cookie1), but for some reason when I try to push it into the array, it just pushes in 'key' instead of the actual variable.
Below is the full function, any ideas would be greatly appreciated. Thanks.
var loop = [];
cookie_objects(req.cookies);
function cookie_objects( cookies ) {
for (var cookie in cookies) {
if ( cookie != 'seen_cookie_message' && cookie != '_ga' ) {
var key = cookie;
var value = cookies[cookie];
loop.push({key : value});
}
}
}
You have to create the blank object beforehand - then assign the key via bracket notation:
var obj = {};
obj[key] = value;
loop.push(obj);

Javascript setter and getter with key for object

I have an object in a variable var o={};
I want to do something like what .push() method doing in array for my object.
JS code:
// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/
// Object:
var obj={};
/* obj.push('key','value'); // I want do something like this
var got2=obj.getVal('key'); // And this
*/
Is this possible at all ?
var obj = {}
// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'
// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'
// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK
Since Object-Literals use a Key->Value model, there is no JS method to "push" a value.
You can either use Dot Notation:
var Obj = {};
Obj.foo = "bar";
console.log(Obj);
Or Bracket Notation:
var Obj = {},
foo = "foo";
Obj[foo] = "bar";
Obj["bar"] = "foo";
console.log(Obj);
Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, as arming yourself with this knowledge will be invaluable in the future.
Here is some javascript magic that makes it work.
Take a look.
var obj = {};
Object.defineProperty(obj,'push',{
value:function(x,y){
this[x]=y;
}
});
obj.push('name','whattttt'); <<<this works!!!
obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt
The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. So if you have 3 items in object this would have always been the 4th one. And mess up the loops always. However, using this method. You can make properties hidden but accessible.
Though i don't know why you would use this method when there is already a easy way to do it.
to assign a value do this
obj.variable = 'value';
if value key is number or weird do this...
obj[1] = 'yes';
to access number or weird name you also do that
obj[1];
and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too.
var person= 'him';
obj[him]='hello';

Problems create multidimensional array in localstorage

I'm trying to save some data in localstorage. My script looks like this:
localStorage.clear(); //only for testing
if(typeof localStorage.akten == "undefined") {
localStorage.akten = new Array();
}
var nam = "alpha";
localStorage.akten[nam] = {
"beta": 12
};
localStorage["a_akte"] = nam;
But if I do console.log(localStorage); or console.log(localStorage.akten); akten is only an empty string? Why? With an normal object instead of localStorage it works well.
Suprisingly the devil is in the details. localStorage only stores strings. Encode your objects as JSON before depositing them there using for example JSON.stringify() and JSON.parse().
This is because localStorage is not an Object; it's an interface. You can only assign a String to it, and the best way to do so is with localStorage.setItem. If you want to be setting more complex data, you'll need to encode it as JSON first.
function localStore(key, obj) {
return window.localStorage.setItem(key, JSON.stringify(obj));
}
function localGet(key) {
return JSON.parse(window.localStorage.getItem(key));
}
localStore('foo', {bar: 'baz'});
localGet('foo'); // Object {bar: "baz"}

Categories

Resources