Concatenating a value onto the end of an object property? - javascript

I'm saving user preferences using localStorage, like this:
choicesObject = { //put values in an object
"measure1" : $("#m1").is(':checked'),
"measure2" : $("#m2").is(':checked'),
"measure3" : $("#m3").is(':checked'),
"measure4" : $("#m4").is(':checked'),
"measure5" : $("#m5").is(':checked'),
"measure6" : $("#m6").is(':checked'),
"measure7" : $("#m7").is(':checked'),
"measure8" : $("#m8").is(':checked')
}
localStorage.setItem("choices", JSON.stringify(choicesObject));
Then I'm getting them back out like this:
retrieveChoices = localStorage.getItem("choices");
choicesObject = JSON.parse(retrieveChoices);
for(var i = 0;i<9 ;i++){
This nex t line is the problem:
ticked = choicesObject.measure+i;
It just doesn't work and I've tried using quotes and square brackets.
element = "#m" + i;
if(ticked==true){
$(element).prop('checked', true);
}
else{
$(element).prop('checked', false);
}
}
}
I want to loop though the measure properties and restore the checkbox elements.
I'm aware that even my object create is inefficient and I could use a for loop for that but I just don't know how to deal with object properties when it comes to looping because I don't get how you can do it without breaking the object.
At least that works and I can get data into and out of objects that get stored in localStorage, but this really simple issue has me stumped.
PS. Would
choicesObject = localStorage.getItem(JSON.parse("choices"));
be a better shorthand? Just thought this now whilst re-reading my question.
Edit: Thanks everyone. I got 3 correct answers so quickly! Amazing. Thanks so much. This site and its members amaze me every day and have revolutionised my coding!
I'm going to choose the correct answer as the one that also gave me the new shorthand for my parsing, but all of you gave me what i needed to know. I'm going to go see if I can answer some noob questions now!

Use
ticked = choicesObject["measure"+i];
EDIT: Your shorthand would not work, use instead:
choicesObject = JSON.parse(localStorage.getItem("choices"));

An object is just like a "dictionary" of values, so you can access a property either by doing myobject.propertyName or myobject["propertyname"]. They are equivalent.
In your case you just have to replace ticked = choicesObject.measure+i; with
ticked = choicesObject["measure"+i];
Also, consider using the var keyword when defining variables, each time you ommit it a new global variable will be created in the window object, that is the case for retrievedChoices and choicesObject. You can confirm this by accessing them via window["choicesObject"] or window.choicesObject or just choicesObject anywhere after that script has run.

Related

How to ignore duplicate values and append only unique values in local-storage?

Can anyone please help me. I am appending the data in local storage and it is taking duplicate values as well. Anyone know how to ignore duplicate values and append only unique values? I tried to check other similar types of stack-overflow, but not work for me, please help me!
Please see the attached code and its output for reference:-
getProgramDetails = (ppTermDetails) => {
this.programDetails = ppTermDetails;
var entry = this.programDetails;
sessionStorage.setItem("entry", JSON.stringify(entry));
var allEntries = JSON.parse(sessionStorage.getItem("allEntries")) || [];
allEntries.push(entry);
sessionStorage.setItem("allEntries", JSON.stringify(allEntries));
};
Please see the attached output for better understanding
Maybe a better way would be to use object and use programPerTermId as a key and so the new one would override the old one rather than having to loop through the array to find the duplicate one
assuming the programPerTermId is unique
{
75: {programPerTermId: 75,....}
}
getProgramDetails = (ppTermDetails) => {
sessionStorage.setItem("entry", JSON.stringify(ppTermDetails));
var allEntries = JSON.parse(sessionStorage.getItem("allEntries")) || {};
//we will use the programPerTermId as a key for the object
//and will store the object as the value
allEntries[ppTermDetails.programPerTermId] = ppTermDetails;
sessionStorage.setItem("allEntries", JSON.stringify(allEntries));
};
but if you still want to go with your idea then you can check this thread and this, check the comments on the same topic

Passing PHP array to JAVASCRIPT (issue)

There's some weird issue it seems.
I'm trying to pass a php array to js, which I've accomplished. I can display the array size like so
document.getElementById("test").innerHTML = (jarr.length);
and it works perfectly fine, however, when I try to display a value in said array, it says object Object
and what's weird is if I go try to read a value which isnt stored, for example jarr[234] it says undefined because there's no value stored, so I know some data is being transferred.
Any help?
edit: here's how I passed the array to js
var jarr = <?php echo json_encode($testing); ?>;
edit: I forgot the remove the parse part before copying it, I was experimenting beforehand.
You should be able to just directly use jarr without parsing it, for example:
document.getElementById("test").innerHTML = jarr.length;
document.getElementById("first_element").innerHTML = jarr.length > 0 ? jarr[0] : "empty array";
If you are doing the above and the elements are showing up as object Object it means that inside your array, you are storing objects rather than primitive data types. So maybe try something like the following to generate a nice string representation of those objects (noting that this is needed for displaying them, but not for using them directly in your JavaScript code):
document.getElementById("first_element").innerHTML = jarr.length > 0 ? JSON.stringify(jarr[0]) : "empty array";
What Chris said fixed the issue!
"To show the entire array: document.getElementById("test").innerHTML = JSON.stringify(jarr); To show a single string: document.getElementById("test").innerHTML = jarr[0]; – Chris G 7 mins ago
"
For whatever reason adding the (stringify) fixes it for me.
An example
document.getElementById("test").innerHTML = JSON.stringify(jarr[2].title);

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

How to access first or specific object from json data

I have a json file with below mentioned format
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
I will be reading above file data using jquery as mentioned below
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").
Thanks
There are several ways of doing it
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order.
hope it helped
Try this code
nodes['aidan']
edges['Quinn']
Either the before mentioned code
nodes['aidan']
or
nodes.aidan
should work equally fine.
Prepared a fiddle for you. You can check there.

pushing json arrays in javascript

I am customizing some jQuery plugin, and I have an error message I can't understand
var totHistory=0;
var positions = new Array();
$('.someclass').each(function(index){
var tmp = $(this).val();
addHistory({id:tmp});
});
function addHistory(obj)
{
/* Gets called on page load for each comment, and on comment submit */
totHistory++;
positions.push(obj.id);
}
At the very first iteration through .someClass, I get this message
Cannot call method 'push' of undefined
Could someone explain why ?
You should either send positions as a parameter or declare it in a scope accesible for addHistory. You should not declare it without the var keyword as that is considered a bad practice.
Try my first suggestion as that one is the only one I can help you with without knowing the structure of your other js code.

Categories

Resources