How to overwrite a json object? - javascript

I have json object with a key named favorite, it has a value of true, when the button is pressed I want to overwrite the value of the favorite key to false and vica versa.
This is what`s inside the json object:
allPlaces: "[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite":false}]"
function favourite(element) {
var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));
var placeIndex = element.getAttribute("data");
places = {allPlaces}
if (allPlaces["favourite"] == true) {
places.favourite[placeIndex] = false;
element.querySelector('ion-icon').setAttribute('name', 'star-outline');
} else {
console.log("working");
places.favourite[placeIndex] = true;
element.style.color = '#FFE234';
element.querySelector('ion-icon').setAttribute('name', 'star');
}
localStorage.setItem("allPlaces", JSON.stringify(places));
}

allPlaces is an array (in this case it has 1 item) so therefore in order to change the property of an object inside it you have to give it an index like so allPlaces[0].favorite = true
I added some code as a reference
const allPlaces = '[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite":false}]';
const places = JSON.parse(allPlaces);
places[0].favorite = true;
console.log(places[0]);

Related

JavaScript - Issues recovering a map in an object after being saved in localStorage

I've been dealing with this for some time. I've a list of sections in which the user checks some checkboxes and that is sent to the server via AJAX. However, since the user can return to previous sections, I'm using some objects of mine to store some things the user has done (if he/she already finished working in that section, which checkboxes checked, etc). I'm doing this to not overload the database and only send new requests to store information if the user effectively changes a previous checkbox, not if he just starts clicking "Save" randomly. I'm using objects to see the sections of the page, and storing the previous state of the checkboxes in a Map. Here's my "supervisor":
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
var children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children().length;
for (var i = 0; i < children; i++) {
if (i % 2 == 0) {
var checkbox = $("#ContentPlaceHolder1_checkboxes_div_" + id).children()[i];
var idCheck = checkbox.id.split("_")[2];
this.selections.set(idCheck, false);
}
}
console.log("Length " + this.selections.size);
this.change = false;
}
The console.log gives me the expected output, so I assume my Map is created and initialized correctly. Since the session of the user can expire before he finishes his work, or he can close his browser by accident, I'm storing this object using local storage, so I can change the page accordingly to what he has done should anything happen. Here are my functions:
function setObj(id, supervisor) {
localStorage.setItem(id, JSON.stringify(supervisor));
}
function getObj(key) {
var supervisor = JSON.parse(localStorage.getItem(key));
return supervisor;
}
So, I'm trying to add to the record whenever an user clicks in a checkbox. And this is where the problem happens. Here's the function:
function checkboxClicked(idCbx) {
var idSection = $("#ContentPlaceHolder1_hdnActualField").val();
var supervisor = getObj(idSection);
console.log(typeof (supervisor)); //Returns object, everythings fine
console.log(typeof (supervisor.change)); //Returns boolean
supervisor.change = true;
var idCheck = idCbx.split("_")[2]; //I just want a part of the name
console.log(typeof(supervisor.selections)); //Prints object
console.log("Length " + supervisor.selections.size); //Undefined!
supervisor.selections.set(idCheck, true); //Error! Note: The true is just for testing purposes
setObj(idSection, supervisor);
}
What am I doing wrong? Thanks!
Please look at this example, I removed the jquery id discovery for clarity. You'll need to adapt this to meet your needs but it should get you mostly there.
const mapToJSON = (map) => [...map];
const mapFromJSON = (json) => new Map(json);
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
this.change = false;
this.selections.set('blah', 'hello');
}
Supervisor.from = function (data) {
const id = data.id;
const supervisor = new Supervisor(id);
supervisor.verif = data.verif;
supervisor.selections = new Map(data.selections);
return supervisor;
};
Supervisor.prototype.toJSON = function() {
return {
id: this.id,
verif: this.verif,
selections: mapToJSON(this.selections)
}
}
const expected = new Supervisor(1);
console.log(expected);
const json = JSON.stringify(expected);
const actual = Supervisor.from(JSON.parse(json));
console.log(actual);
If you cant use the spread operation in 'mapToJSON' you could loop and push.
const mapToJSON = (map) => {
const result = [];
for (let entry of map.entries()) {
result.push(entry);
}
return result;
}
Really the only thing id change is have the constructor do less, just accept values, assign with minimal fiddling, and have a factory query the dom and populate the constructor with values. Maybe something like fromDOM() or something. This will make Supervisor more flexible and easier to test.
function Supervisor(options) {
this.id = options.id;
this.verif = null;
this.selections = options.selections || new Map();
this.change = false;
}
Supervisor.fromDOM = function(id) {
const selections = new Map();
const children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children();
for (var i = 0; i < children.length; i++) {
if (i % 2 == 0) {
var checkbox = children[i];
var idCheck = checkbox.id.split("_")[2];
selections.set(idCheck, false);
}
}
return new Supervisor({ id: id, selections: selections });
};
console.log(Supervisor.fromDOM(2));
You can keep going and have another method that tries to parse a Supervisor from localStorageand default to the dom based factory if the localStorage one returns null.

How to use localStorage to save variable with random value

I'm trying to use localStorage to save a variable with value generated randomly from an array in a JavaScript file, and pass it to another HTML file. However, the value in Javascript file (Random_Msg) and the value in HTML file (Random_Msg1) are not the same, means it's not saved, instead it generated randomly another value.
These are the code to generate variable and save in localStorage:
function CreateRandomMsg(){
var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
return RandomMsg;
}
var Random_Msg = CreateRandomMsg();
function alertMsg(){
alert(Random_Msg);
}
window.localStorage.setItem("Random_Msg1",Random_Msg);
In my HTML file, I just retrieved the variable first:
var Random_Msg1 = window.localStorage.getItem("Random_Msg1");
And use it in if statement:
if (Random_Msg1 == Msgs_Arr[0] || Random_Msg1 == Msgs_Arr[1]){
value = facesDet.photos[0].tags[0].attributes.glasses.value;
confidence = facesDet.photos[0].tags[0].attributes.glasses.confidence;
} else if (Random_Msg1 == Msgs_Arr[2] || Random_Msg1 == Msgs_Arr[3]) {
value = facesDet.photos[0].tags[0].attributes.smiling.value;
confidence = facesDet.photos[0].tags[0].attributes.smiling.confidence;
};
You can check on pageload if value for necessary key exists in localStorage. If value is missing, then compute and save new value. You can also have an extra event on which you can override value of this key, but this will be a user action.
Note: Stack Overflow does not give access to localStorage and any testing should be done on JSFiddle.
Sample
JSFiddle
function computeRandomValue() {
var data = ["test", "test1", "test2", "test3", "test4"];
var index = Math.floor(Math.random() * 10) % data.length;
return data[index];
}
function setToLocalStorage(newVal) {
var lsKey = "_lsTest";
localStorage.setItem(lsKey, newVal);
}
function getFromLocalStorage() {
var lsKey = "_lsTest";
return localStorage.getItem(lsKey);
}
function initializePage() {
var _val = getFromLocalStorage();
if (!(_val && _val.trim().length > 0)) {
_val = computeAndSaveNewValue();
}
printValue(_val, "lblResult");
}
function computeAndSaveNewValue() {
var newVal = computeRandomValue();
setToLocalStorage(newVal);
printValue(newVal);
return newVal;
}
function printValue(value) {
var id = "lblResult";
document.getElementById(id).innerHTML = value;
}
(function() {
window.onload = initializePage;
})()
<p id="lblResult"></p>
<button onclick="computeAndSaveNewValue()">Save new Value</button>

how to change attribute text of json in jquery?

I am trying to change the property name /attr name of my json object.I try like that but nothing will change.I need to make json object after seen the input json and convert it like outjson
function changeData(data){
var title;
for(var i = 0; i < data.length; i++){
if(data[i].hasOwnProperty("displayName")){
data[i]["label"] = data[i]["displayName"];
delete data[i]["displayName"];
}
if(data[i].hasOwnProperty("displayDetail")){
data[i]["title"] = data[i]["displayDetail"];
delete data[i]["displayDetail"];
}
if(data[i].hasOwnProperty("inputType")){
if(data[i]["inputType"]=="NUMBER"){
data[i]["type"]="number"
}else if(data[i]["inputType"]=="TEXT"){
data[i]["type"]="text"
}else if(data[i]["inputType"]=="SWTICH"){
data[i]["type"]="select"
}
delete data[i]["inputType"];
}
}
console.log(data);
}
Try this - it's possibe to remove the if selection for inputType by creating a tiny lookup table from original value to new value:
function changeData(data) {
var map = { NUMBER: "number", TEXT: "text", SWITCH: "select" };
// data is an object - use for .. in to enumerate
for (var key in data.input) {
var e = data.input[key]; // alias for efficient structure dereferencing
e.label = e.displayName;
e.title = e.displayDetail;
e.type = map[e.inputType];
delete e.displayName;
delete e.displayDetail;
delete e.inputType;
}
};
There's really no need for the hasOwnProperty test these days - only use it if you think there's any risk that someone unsafely added to Object.prototype. jQuery manages without it quite happily, other modern code should do to.
If the mapping of field names was any longer I'd consider using another mapping table with another loop to remove the hard coded copy/delete pairs.
i have a nice Recursive function for that:
usage:
// replace list
var replacedObj = replaceAttrName(sourceObject, {foo: 'foooo', bar: 'baaar'});
so in your case you can easily do:
var newObj = replaceAttrName(json, {displayDetail: 'title', displayName: 'label', inputType: 'type'});
demo: http://jsfiddle.net/h1u0kq67/15/
the function is that:
function replaceAttrName(sourceObj, replaceList, destObj) {
destObj = destObj || {};
for(var prop in sourceObj) {
if(sourceObj.hasOwnProperty(prop)) {
if(typeof sourceObj[prop] === 'object') {
if(replaceList[prop]) {
var strName = replaceList[prop];
destObj[strName] = {};
replaceAttrName(sourceObj[prop], replaceList, destObj[strName]);
} else if(!replaceList[prop]) {
destObj[prop] = {};
replaceAttrName(sourceObj[prop], replaceList, destObj[prop]);
}
} else if (typeof sourceObj[prop] != 'object') {
if(replaceList[prop]) {
var strName = replaceList[prop];
destObj[strName] = sourceObj[prop];
} else if(!replaceList[prop]) {
destObj[prop] = sourceObj[prop];
}
}
}
}
return destObj;
}
If I am getting you right, you just want substitutions:
displayDetail => title
displayName => label
inputType => type.
I came up with the follwoing:
function changeData(data){
return JSON.parse(JSON.stringify(data).replace(/displayDetail/g, "title").replace(/displayName/g, "label").replace(/inputType/g, "type"));
}
Here is the Fiddle to play with.
Edit: I forgot replacements for "NUMBER", "TEXT" and "SWITCH".
function changeData(data){
return JSON.parse(JSON.stringify(data).replace(/displayDetail/g, "title").replace(/displayName/g, "label").replace(/inputType/g, "type").replace(/TEXT/g, "text").replace(/NUMBER/g, "number").replace(/SWITCH/g, "switch"));
}

Access js array in another js file

I fill my array in the checklistRequest.js and I want to access it in my Termine_1s.html file which contains js code. I can access it but when I want to iterate through it, it gives me only single digits instead of the strings.
How can I solve this?
checklistRequest.js
//Calls the checkbox values
function alertFunction()
{
//Retrieve the object from storage
var retrievedObject = localStorage.getItem('checkboxArray');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
return retrievedObject;
}
Termine_1s.html
//Checks if title was checked already
var checklistRequest = alertFunction();
var titleAccepted = true;
for (var a = 0; a < checklistRequest.length; a++)//Iterates through whole array
{
if(title != checklistRequest[i] && titleAccepted == true)//Stops if false
{
titleAccepted = true;
}
else
{
titleAccepted = false;
}
}
you need to parse the object at some point.
Try:
return JSON.parse(retrievedObject);

Reference issue with Javascript

I have an array of objects cached on client side using JS array.
var scannerDictionary = new Array(); //Holds all scanners unmodified
var modifiedScannerDictionary = new Array(); //Holds all scanners with modified values
The properties of each object is set/changed using GUI and updated in the object. Each object contains list of InputParameters (array of Parameter class containing Name, Value and other members).
Please have a look on GUI.
Below is the code i used to render the controls -
function renderControls(scannerId) {
var currentScanner = modifiedScannerDictionary[scannerId];
//Render Input Parameters
$("#tblInputCriteria").find('tr:gt(5)').remove();
for(var i=0;i<currentScanner.InputParameters.length;i++) {
var propType = currentScanner.InputParameters[i].DataType;
var inParName = currentScanner.InputParameters[i].Name;
switch(propType) {
case 0: //Number
var eRow1 = $("#tblInputCriteria").find('#emptyNumRow').clone();
$(eRow1).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow1).appendTo($('#tblInputCriteria'));
var prop1 = $(eRow1).find('#InNumPropName');
$(prop1).attr('id', 'InNumPropName_'+currentScanner.InputParameters[i].Name);
var propName1 = currentScanner.InputParameters[i].Name;
$(prop1).html(propName1);
var propVal1 = $(eRow1).find('#InNumPropValue');
$(propVal1).attr('id', 'InNumPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal1).val(currentScanner.InputParameters[i].Value);
$(propVal1).blur(function () {
if(!ValidateNumber(this, propName1)) {
alert('Value should be numeric in ' + propName1);
setTimeout(function() {$(propVal1).focus();}, 100);
}else {
UpdateData(currentScanner.Id, propName1, $(propVal1).val());
}
});
break;
case 1: //String
var eRow2 = $("#tblInputCriteria").find('#emptyStrRow').clone();
$(eRow2).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow2).appendTo($('#tblInputCriteria'));
var prop2 = $(eRow2).find('#InStrPropName');
$(prop2).attr('id', 'InStrPropName_'+currentScanner.InputParameters[i].Name);
var propName2 = currentScanner.InputParameters[i].Name;
$(prop2).html(propName2);
var propVal2 = $(eRow2).find('#InStrPropValue');
$(propVal2).attr('id', 'InStrPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal2).val(currentScanner.InputParameters[i].Value);
$(propVal2).blur(function () {
UpdateData(currentScanner.Id, propName2, $(propVal2).val());
});
break;
case 2: //Boolean
var eRow3 = $("#tblInputCriteria").find('#emptyBoolRow').clone();
$(eRow3).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow3).appendTo($('#tblInputCriteria'));
var prop3 = $(eRow3).find('#InBoolPropName');
$(prop3).attr('id', 'InBoolPropName_'+currentScanner.InputParameters[i].Name);
var propName3 = currentScanner.InputParameters[i].Name;
$(prop3).html(propName3);
var propVal3 = $(eRow3).find('#InBoolPropValue');
$(propVal3).attr('id', 'InBoolPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal3).val(currentScanner.InputParameters[i].Value);
$(propVal3).blur(function () {
UpdateData(currentScanner.Id, propName3, $(propVal3).val());
});
break;
}
}
}
PROBLEM:
The problem here is of the variables inside switch working as reference variable. So the UpdateData() function gets the last Name for similar type properties. i.e. if fields are of Number type then only the last property is updated by UpdateData() method.
Can anybody help me out solve this issue. Thanks for sharing your time and wisdom.
Try something like the following. Its a tad overkill, but will bind the values of the variables to the closures.
var fnOnBlur = (function(thePropName, thePropVal) {
return function () {
if(!ValidateNumber(this, thePropName)) {
alert('Value should be numeric in ' + thePropName);
setTimeout(function() {$(thePropVal).focus();}, 100);
}else {
UpdateData(currentScanner.Id, thePropName, $(thePropVal).val());
}
};
})(propName1, propVal1);
$(propVal1).blur( fnOnBlur );
The link that Felik King supplied has much more detailed discussion.

Categories

Resources