Insert a fresh item into a designated spot without the ability to delete the existing item in that same spot

Greetings! I am looking to insert an item at a specific position and then add another item at the same position. Here is the JSON data:

// To remove item at particular position
var get_delete_position = JSON.parse(localStorage.getItem("user_login_users"));
var new_delete_position = storedNames.slice(pos+1, get_delete_position.length);
localStorage.setItem("user_login_users", JSON.stringify(arr1));

var arr1 = JSON.parse(localStorage.getItem("user_login_users"));
arr1[pos].name = nome_users.value;
arr1[pos].surname = cognome_users.value;  
localStorage.setItem("nome_users", arr1[pos].name);
localStorage.setItem("surname_users", arr1[pos].surname);

var t = {
    name: arr1[pos].name,
    surname: arr1[pos].surname
}

arr1.push(t);
localStorage.setItem("user_login_users", JSON.stringify(arr1));

The local storage successfully adds a new position in memory, sets the new item but does not remove the old item "Patrick Smith". Why is this happening? How can I resolve it?

Answer №1

This is reminiscent of the query you posed yesterday, with the same principles in play.

  1. Retrieve the most recent value from local storage by using localStorage.getItem
  2. Implement your desired changes, whether it involves adding a new item, removing an existing one, or modifying an existing entry—it doesn't make much difference.
  3. Save the modifications back by utilizing localStorage.setItem

Check out the provided example below; feel free to experiment here
It demonstrates adding, deleting, and altering existing entries.

// Setting up local storage for this demonstration: 
localStorage.setItem("user_login_users", JSON.stringify([{
  name: "Elena",
  surname: "Rondina"
}, {
  name: "Lars",
  surname: "Codemonkey"
}]));

// Adding a new user
// Retrieve the user_login_users data from local storage
var usersInLocalStorageAdd = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("before addition:", usersInLocalStorageAdd)
// Add the new user to the object
usersInLocalStorageAdd.push({
  name: "Jacky",
  surname: "Chan"
});
// Save the change to local storage
localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageAdd));
// The new user has now been saved
// The user at the specified position has been deleted:
var afterAdd = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("after addition:", afterAdd)


// Deleting an entry:
// Retrieve the user_login_users data from local storage
var usersInLocalStorageDelete = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("before deletion:", usersInLocalStorageDelete)

// Remove a single user from local storage at the indicated position:
var pos = 0;
if (usersInLocalStorageDelete.length > pos + 1) {
  usersInLocalStorageDelete.splice(pos, 1);
  localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageDelete));

  // The user at the given position has been deleted:
  var afterDelete = JSON.parse(localStorage.getItem("user_login_users") || []);
  console.log("after deletion:", afterDelete)
}


// Modifying an existing user:
// Retrieve the data from local storage once more
var usersInLocalStorageForModification = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log('before modification', usersInLocalStorageForModification)
// Define the values we wish to apply
var firstName = {
  value: "John"
};
var lastName = {
  value: "Smith"
};
// Since pos is still zero, we will alter the first entry.
usersInLocalStorageForModification[pos].name = firstName.value;
usersInLocalStorageForModification[pos].surname = lastName.value;
// The entry has now been modified. We must save it again to retain these changes.
localStorage.setItem("user_login_users", JSON.stringify(usersInLocalStorageForModification));

// The user at the specified position has been modified:
var afterModify = JSON.parse(localStorage.getItem("user_login_users") || []);
console.log("after modification:", afterModify)

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

Is the line between strict and transitional blurred by HTML5?

After conducting research, it seems like HTML5 has done away with the strict versus transitional differentiation (now always strict). Although I haven't found any explicit mention of this change, it is definitely implied. Can you confirm if this is in ...

Ways to eliminate a single child from a jQuery object without altering the HTML structure

My code snippet looks like this: $.fn.extend({ del: function() { } }) var ds = $(".d"); ds.del(ds[0]) console.log(ds.length) I am trying to use jquery.del to remove a child from some jquery elements without altering the HTML. Any suggest ...

Tips for sending a JavaScript object from PHP to AJAX

I've been racking my brain for hours, scouring through countless articles, but I'm still unable to crack this puzzle. Here's the situation: I'm currently tinkering with Chrome extensions and I need to make a server call that will fetch ...

To trigger a pop-up window displaying a link upon clicking the submit button

I am attempting to create a popup box that displays an application accepted message and a link back to the home page upon clicking the submit button. However, the .popup box is not appearing after validation. This is the content that should be displayed w ...

Issue with overwriting variables in Bootstrap 5 has been identified

Attempting to customize default variables by replacing them with my own values. Utilizing the example code provided in the Bootstrap documentation: // 1. Begin by importing functions first (for manipulating colors, SVGs, calc, etc) @import "../bootst ...

What is the best way to define a function that declares and returns an array for global use

I'm attempting to globally declare an array from a function so that it can be accessed by other functions as well. However, I'm unsure how to do this because the code involves a csvtojson converter which complicates things. I'm wondering if ...

Achieving True WYSIWYG Performance in TinyMCE 4.x: Tips and Tricks

Currently, I am in the process of developing a custom CMS where I am integrating tinymce to empower users to create page content, similar to what is seen on Wordpress. The content inputted by users in the admin area will be showcased within a designated el ...

Monitoring and refining console.error and console.log output in CloudWatch

I've encountered a situation where my lambda function includes both console.error and console.log statements, which Node.js interprets as stderr and stdout outputs respectively. However, upon viewing the logs in CloudWatch, I noticed that they appear ...

Transform your TypeScript code with a jscodeshift codemod that removes generic type declarations while preserving the wrapped

I am currently working on developing a codemod that will eliminate all instances of the $ReadOnly<T> generic from a TypeScript codebase, while retaining only T (where T represents an object or union). This is what I have managed to come up with so f ...

Is there a way to reference the button within an if statement in PHP code?

I'm new and struggling with calling a button inside an if statement. I'm working on a user log feature where clicking a button will output to the user log. How can I call the VIEW button inside my if statement so that it uses fwrite to write to ...

Implementing PHP function upon clicking an HTML button

Hey there! I'm trying to trigger the bb() function when a button is clicked. Unfortunately, the code below isn't working as expected. Can you help me out? echo "<div class ='i2' id=".$x.">"; echo "<button type='button&ap ...

Styling an HTML table with two columns: one column displaying an image, and the other column containing information related to the image

I have a concept that involves creating a table with 2 columns. The left column will feature an image, while the right column will display data about the image in 6 rows. ________________________________ | |_______________| | | ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

Customizing individual characters within HTML text using the mouse's current location

Is there a way to manipulate the css properties of individual characters within a text string based on their proximity to the mouse cursor? If you're interested, check out this Codepen: https://codepen.io/NewbCake/pen/qYXvoo The concept involves tak ...

Changing the boolean value within a nested array using Mongoose

I am struggling with updating the boolean value of flagged comments in a Schema that holds an array of objects for comments. I have attempted to use updateOne and aggregate methods, as well as $elemMatch, but so far, none of them have worked. Additionally, ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

jQuery auto-complete feature that cannot be edited

We are experimenting with implementing a non-editable jQuery auto-complete feature. For example, when a user selects a value from the auto-complete dropdown, they should not be able to modify it. However, if they press the backspace key, the old value shou ...

Unable to unfollow using js code

JavaScript Fiddle In my current project, I am implementing follow and unfollow buttons. The follow functionality is working smoothly, but I'm facing an issue with the unfollow button. When I click on it, it doesn't switch back to follow. You can ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

Uncertain about the request path that is being transmitted to my Express server via AJAX

I have a simple Node.js Express server setup My goal is to serve html files by using res.sendFile with this route handler: router.get('/:run_id/:test_num',function(req,res,next){ var runId = req.params.run_id; var testNum = req.params. ...