I have a piece of code that is supposed to search a JSON array in localStorage and modify the isTaken
value inside the specific "equipment" (for example I'm trying to take a 250ml Flask so I enter the equipment name "250ml flask" and I modify the isTaken value of that flask to true
)
JSON is formatted as such:
equipmentdata = [
{
"id":1649778788049,
"name":"500ml Flask",
"type":"Flask",
"isTaken":false,
"dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
},
{
"id":1649778800655,
"name":"250ml Flask",
"type":"Flask",
"isTaken":false,
"dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
},
{
"id":1649778809178,
"name":"Measuring Cylinder",
"type":"mesCyl",
"isTaken":false,
"dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
}
]
My JS is as follows,
function takeHandler() {
const date = new Date();
let finalD = date.toUTCString();
let teachName = document.getElementById("name").value;
let equipmentName = document.getElementById("eqname").value;
let output = teachName " took " equipmentName " at " finalD;
localStorage.setItem("equipmentTaken", null);
var eqhis = JSON.parse(localStorage.getItem("equipmentTaken")) || [];
eqhis.push(output)
localStorage.setItem("equipmentTaken", JSON.stringify(eqhis));
let finalout = localStorage.getItem("equipmentTaken");
document.getElementById("output").innerHTML = finalout;
var currentData = localStorage.getItem("equipmentdata");
currentData = currentData ? JSON.parse(currentData) : {};
currentData[eqname, isTaken] = true;
}
The main error is the the last line, I'm not really good at javascript and I cant really get the "eqname" value from the JSON and replace its "isTaken" value with true
my expected output would look like this
{
"id":1649778800655,
"name":"250ml Flask",
"type":"Flask",
"isTaken":true,
"dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
},
CodePudding user response:
try this, it was tested and working properly
var currentData = localStorage.getItem("equipmentdata");
currentData = currentData ? JSON.parse(currentData) : {};
updateIsTaken(currentdata,"250ml Flask");
localStorage.setItem("equipmentdata", currentdata);
function updateIsTaken(equipment, name)
{
equipment.forEach(item => {
if(item.name==name)
{
item.isTaken=true;
}
});
}
And I don't know how to you keep data in a local storage, so maybe you don't need to parse.
CodePudding user response:
Invalid syntax.
// Invalid assignment, this doesn't work in javascript. We need the key as a string
currentData[eqname, isTaken] = true;
// Should be
currentData['eqname'] = true;
currentData['isTaken'] = true;
// As a oneliner, assign object directly. Here we don't need string flaps
currentData = { eqname: true, isTaken: true }