add a value to localstorage, instead of replacing it - javascript

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code, it replaces the entire value.
Code
$('#signUpButton').click(function() {
var newUsername = $('#usernameSignInBox').val();
signedUpUsernames.push(newUsername);
localStorage.setItem('setUsernamesArray', signedUpUsernames);
});

If you want to add to the array, you must realise that the value in localStorage isn't an array, it is a string. If you want that string to represent an array, and you want to update that array, you must do the following things:
read the string, localStorage.getItem('setUsernamesArray'),
then convert it to an array with JSON.parse,
then push to the array,
and then store it again with localStorage.setItem('setUsernamesArray', JSON.stringify(array))

localStorage always store values as a string, so stringify your array and store,
localStorage.setItem('setUsernamesArray', JSON.stringify(signedUpUsernames));
And before reading it just parse it,
var arrayFrmStorage = JSON.parse(localStorage.getItem("setUsernamesArray"))

localStorage.setItem will replace value of the key in localStorage.
Consider localStorage as a variable. when you do
var a = "Hello";
a = " World"
value of a is replaced. To avoid it, we use +=
var a = "Hello";
a += " World"
Similarly, you will have to create another object with updated value and write this to localStorage.
Following is an example.
function setValueToLS(key, prop, value){
var _local = {};
if(localStorage.getItem(key))
_local = JSON.parse(localStorage.getItem(key));
_local[prop] = value;
localStorage.setItem(key, JSON.stringify(_local));
}

Related

Unwanted undefined in the web page output [duplicate]

I have a function that concatenates together the results from an AJAX request.
For some reason, my final string starts with "undefined".
Here is a simplified example that reproduces the problem:
// In practice, fetched via AJAX from a server
var vendors = [{ id_vendor: 'V0001' }, { id_vendor: 'V0002' }];
var row_vendor;
vendors.forEach(function (value) {
row_vendor += value.id_vendor;
});
alert(row_vendor); // undefinedV0001V0002
Why does the value alerted display a leading "undefined"?
You're not initializing your variable, so its value is undefined. Concatenating a string coerces it to the string "undefined" before the concatenation.
Consider:
var x
alert(x + "test") // undefinedtest
Instead, initialize your variable to an empty string before performing concatenation:
var x = ""
alert(x + "test") // test
Note that functionally it is much cleaner to first extract the property you're interested in and then simply join them together:
$.map(vendor, function (v) { return v.vendor_id }).join('')
Your row_vendor variable is not assigned an initial value, so it starts out undefined and then using the += operator on it to concatenate a string results in undefined becoming the string "undefined" (plus the "v0001"). Simply set it to an empty string when you declare it:
var row_vendor = "";
The issue is on this line
$.each(vendor, function(i, value) {
row_vendor += value.id_vendor;
});
In order to use row_vendor for concatenation purpose, you first have to have a default value assigned to it. So what you would need to do is:
var row_vendor = ""; // set it to empty string by default
$.each(vendor, function(i, value) {
row_vendor += value.id_vendor;
});
On a sidenote, you can also concatenate a string using an array. I prefer it this way since it's more pretty and readable.
var row_vendor = []; // empty array
$.each(vendor, function(i, value) {
row_vendor.push(value.id_vendor);
});
console.log(row_vendor.join(",")); // this will separate each value with a comma

Print JSON path and variable result in one call in JavaScript

Is it possible to console.log something like this:
myParent.myChildData(5)
(variable literal name + value in brackets)
from a JSON object such as this:
{myParent: {myChildData: 5}}
I would like to do it with referencing the object notation ideally only once. Something like:
console.log(printExpression(myParent.myChildData))
Where printExpression I'm certainly happy to be a generic helper function that could return this. I've searched high and low, but obviously printExpression receives the actual evaluated value and this causes a road block.
You can turn JSON into a JavaScript object by using JSON.parse(jsonString).
You can store that as a variable and then console.log it.
Or you can just directly console.log the passed data like this:
console.log(JSON.parse('{"myparent":{"myChildData": 5}}').myParent.myChildData);
Edit
After understanding what exactly the helper function does, I've created a printExpression function that returns string values based on your example.
function printExpression(object, stringBefore) {
//Recursively make objects with keys as methods
let newObject = {};
for (var key in object) {
//Make sure the key exists on the object
if (object.hasOwnProperty(key)) {
let value = object[key];
//If the value is an object, just add a get method that returns the object
if (typeof(value) == "object") {
let childObject = printExpression(value, key + ".");
newObject[key] = childObject;
}
//If not, make a method that returns the wanted syntax
else {
//Form the string based on specific syntax
let str = key + "(" + value + ")";
//Check if we should add stringBefore
if (stringBefore) {
str = stringBefore + str;
}
newObject[key] = str;
}
}
}
//Return the new object
return newObject;
}
var example = printExpression(JSON.parse('{"myParent": {"myChildData": 5}}'));
console.log(example.myParent.myChildData);
How It Works
When creating the helper object, it recursively reads all the keys of the original object and makes a new object that returns the keys in an organized way. For example if the original object was { greeting: "hello" } then newObject.greeting would be "greeting(hello)" (as you said it should be).
Possible Problems
Doesn't get updated when you change the original object. I don't think this will be much of a problem as you seem to be reading static JSON data, but just letting you know.

Parsing Json in Node.js which holds numbers as its key param

My JSON holds numbers in its key param for an example:
"abc_12345_xyz":"value".
I am fetching this 12345 from my property file and framing the key param dynamically, while parsing it. For an example
var num=fetching from prop file(12345).
var jsonValue=jsonObj.value[0].abc_+num+_xyz
I am not getting the value while performing the above step, is there anyway to frame the key parameter dynamically.
Try using
jsonObj.value[0]["abc_"+num+"_xyz"]
If you will have a list in your properties file and want to get the value based on the entry, like using a regex to get any key that have the property content, you can loop through the keys and check if it have the word on the key. See below this example:
var obj = {
"abc_12345_xyz": "test_value_1",
"abc_qwert_xyz": "test_value_2"
};
var prop_file = [12345, 'qwert'];
for (var key in obj) {
if (key.indexOf(prop_file[1]) > -1) {
console.log(key, obj[key]);
}
}
Or if the key will always having the prefix and suffix static, you can simply:
obj["abc_"+ prop_value +"_xyz"];

How to access a value within a JSON Object

I have the following JSON object notation:
[{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}]
and am unsure how to only access the "cname" value alone in JavaScript, i.e. I just require:
"www.fred.com.au"
I have tried res[0].cname but this didn't seem to work.
If you have
let object = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
then you can get that URL value via
let url = object[0]["getCname('mail.fred.com.au')"][0].cname;
The outer object is an array, and the value of the property with the long strange name is also an array, hence the [0] in two places.
This is a bit cludgy but if you don't know the 'getCname' key you can do:
let res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
let key = Object.keys(res[0])[0];
let cname = res[0][key][0].cname;
Try these
var res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
res[0] ;// returns Object {"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]};
res[0]["getCname('mail.fred.com.au')"] ;//returns Array [{"cname":"www.fred.com.au"}];
res[0]["getCname('mail.fred.com.au')"][0].cname ;//returns "www.fred.com.au"

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:
var arrayName = new Array;
arrayName["indexName"] = value;
// i know i can also do the last line like this:
arrayName.indexName = value;
When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:
arrayName[eval("nume")] = value;
Where:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"
Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?
At first I don't think you need a real array object to do what you need, you can use a plain object.
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.
You would use objects to do that:
var hash = {}
hash["foo"] = "foo";
hash.bar = "bar";
// This is the dynamic approach: Your key is a string:
baz = "baz"
hash[baz] = "hello";
To iterate, just use a for loop or $.each() in jQuery.
use arrayName[var1+var2]
Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)
Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?
And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';
You want a plain object with the same bracket notaiton here, like this:
var arrayName = {};
arrayName["indexName"] = value;
Indeed, there was no need for an array object, a simple object did the job; further more an array introduced the need to use quotes inside the square brackets obj["var1 + var2"] to access the object property's value and not the value associated with an index (i think); the quotes transformed "var1 + var2" into a string. Using a simple object eliminated the need for quotes, so I can use obj[var1 + var2], wich worked :)
Thanks everyone !
I did something like like following;
let parentArray = [];
let childArray = [1, 2, 3];
childArray.name = 'my-array-1';
parentArray.push(childArray);
To access that by name in ES6;
parentArray.filter(x => x.name == 'my-array-1');

Categories

Resources