简体   繁体   中英

Update single object in localStorage

I want to update a single Object in my localStorage. I made a detail page, where I can submit new values (progress and value) When I want to update the value, it changes the value in both objects. How can I change just one object.

Here is my deployment link.(its work in progress) https://mastery-app.herokuapp.com/

This is my localStorage array:

skills[
    {
        "title": "Sewing",
        "imageSrc": "images.unsplash.com",
        "description": "Make your own clothes",
        "category": "crafting",
        "progress": 500,
        "isDone": false,
        "rank": 0,
        "value": 0
    },
    {
        "title": "Crocheting",
        "imageSrc": "images.unsplash.com",
        "description": "Interlock loops of yarn",
        "category": "crafting",
        "progress": 500,
        "isDone": false,
        "rank": 0,
        "value": 0
    }
]

This is how I update the localStorage:

const update = skills.map((skills) => {
    skills.title === skills.title;
    const updateProgress = skills.progress - value;
    const rankNumber = parseInt(ranking);
    const updateRank = skills.rank + rankNumber;
    console.log(updateRank);
    const updateValue = skills.value + value;

    return {
      title: skills.title,
      rank: updateRank,
      description: skills.description,
      progress: updateProgress.toFixed(1),
      imageSrc: skills.imageSrc,
      category: skills.category,
      isDone: false,
      value: updateValue,
    };
  });
  localStorage.setItem('skills', JSON.stringify(update));

You may consider using the find method to find the object you want to update. map is not the right function to be used for your use case. Also skills.title === skills.title; has no effect at all (Maybe you wanted to use an if statement to do some kind of filtering by using title but that always would return true). Please remove that.

Now, I don't exactly know which field are you going to use to search for the object you want to update, but it has to be unique. If none of the fields in the objects are unique you should consider adding an unique id field in the skills objects. But if title is unique you can use the title to search. Then you can do something like the pseudo code below:

const toUpdate = skills.find(skill => skill.title === your_title_here)

toUpdate.field_to_update_1 = some_value_1
toUpdate.field_to_update_2 = some_value_2

localStorage.setItem('skills', JSON.stringify(skills))

Please also check the MDN docs to see how map , find and other array methods work and some of their use cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM