The process of updating the value of an element in local storage with JavaScript

Most of the time we have an object stored in our localStorage.

let car = {
    brand: "Tesla",
    model: "Model S"
  };

 localStorage.setItem("car", JSON.stringify(car));

I am now eager to update the value of "model". How do I go about achieving this using Javascript?

(Although the code below isn't functional, it provides a glimpse of what I intend to accomplish)

 localStorage.setItem(localStorage.getItem("car").model, "Model X");

Answer №1

First, you extract the JSON data, then parse it to update the object received from parsing. Next, you convert the updated object back into a string and save this result.

const spaceship = JSON.parse(localStorage.getItem("spaceship"));
spaceship.status = "newStatus";
localStorage.setItem("spaceship", JSON.stringify(spaceship));

An alternative method is to condense it into a single line using Object.assign, but this can make the code more challenging to understand and maintain:

localStorage.setItem("spaceship", JSON.stringify(Object.assign(JSON.parse(localStorage.getItem("spaceship")), {status: "newStatus"})));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please refrain from populating my file with unnecessary data when using writeJSONString

Despite my efforts to write JSON data into a file, this simple piece of code is creating an empty file. import java.io.{File, FileWriter, IOException} import org.apache.http.client.ClientProtocolException import org.apache.http.client.fluent.Request impo ...

Loop through each element in a JSON array using jQuery's `.each()` method

Above is a snippet of my jQuery function: function fetchData(jsonLink){ $(".scrollable .items").html("<img class='loadGif' src='/sites/all/themes/zen/journeyon/images/ajax-loader.gif' alt='' />"); $.ajaxSetup({ ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Which is the preferable option for creating a circular daily planner: canvas or SVG?

As a novice programmer delving into the world of coding (or at least hoping to), I have a question regarding graphic tools in html5 for my latest project. My goal is to create a planner app using electron, with the unique twist that the planner form sho ...

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...

Can Vue.js support two-way data-binding without the use of an input element?

Here is the code snippet that I'm working with: <div id="app"> {{ message }} </div> JavaScript: myObject = {message:"hello"} new Vue({ el: '#app', data: myObject }) When I update myObject.message, the content within th ...

Text centered vertically with jQuery is only loaded after the page is resized

My jQuery script is designed to vertically center text next to an image, but it seems to only work properly after resizing the page. $(window).load(function () { $(function () { var adjustHeight = function () { $('.vertical-al ...

Converting JSON data into XML format with Python

I am looking to convert a large JSON file into an XML file. Here are two lines that I extracted from the JSON file. My goal is to create a root node for every INVENTORY_SEQ_ID found in this file: [{"INVENTORY_SEQ_ID":4577494,"GROUP_NBR":8605548,"SEQ_NBR": ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

"Encountered an OperationalError while trying to insert JSON data into sqlite database: Error message stating that the token "{"" is

In my code, I have implemented something similar to this: import sqlite3 ... sqlString=company['name']+","+simplejson.dumps(info) cur.execute("INSERT INTO companyInfo VALUES("+sqlString+")") However, when running it, I encountered the following ...

Mastering the art of jQuery scrolling: A step-by-step guide

Is there a way to utilize jQuery for scrolling purposes? For example, transforming this: <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#home">Home <span class="sr-only">(current)</span></a> ...

An error with jQuery occurred in the client's post response, resulting in a 400 POST HTTP/1.1 error

I am struggling to identify the issue with my code, especially since I'm not very familiar with jQuery. The goal is to create an HTML form for storing car data based on this template: The source code for the HTML form can be found here. Upon clickin ...

Enable modification of form field once a personalized dynamic stamp has been applied

I currently have a functional custom dynamic stamp that includes multiple input fields prompting the user. My goal now is to integrate a form text field onto the stamp after it has been rendered. For example, if someone stamps everything except for the led ...

How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below: d3.selectAll("svg g rect") .on('mouseover', function (d) { console.log(this); }); When Console.log is executed, the following is printed: <rect class="cls" na ...

JavaScript - Declaring canvas as a global object

Presently, I am experimenting with HTML5 and using JavaScript to create a basic 2D Tile map. Progress is going smoothly; however, I have come across an issue where I am unable to contain everything within one large function. I am attempting to make the ca ...

Guide to transforming a file from a str class type to a Python dictionary

Below is the code snippet I have written: import json with open('json_data.json') as json_file: df = json.load(json_file) This code opens a JSON file that looks like this: {'api_version': None, 'kind': None, 'metad ...

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Tips for retrieving JSON data from an API and displaying it as listview labels in Xamarin using C#:

I have successfully implemented a piece of code that fetches JSON data from an API. By placing a breakpoint on it, I am able to view the JSON content retrieved from the specified URL. Here is how the JSON appears when I set a breakpoint: https://i.stack. ...

Investigate the CSS display property of an element using JavaScript

Can JavaScript be used to determine if an element's CSS display == block or none? ...