Delete JSON element with a value

0

I have a JSON that I get from localStorage where I keep the names of the players and their scores for a game, then I receive them in 2 separate variables to be able to modify the score and increase its value if the player wins. What I want to do is that when the player wins, delete the JSON element and then reinsert it with the modified score value and save it back to localStorage.

That's how I get the JSON:

var Jugadores = localStorage.getItem("Jugadores");
Jugadores = JSON.parse(Jugadores);

This JSON filled it in another html where the players register and in the game page this is what I get in console:

 ["{"player":"leader","score":0}", 
  "{"player":"lel","score":0}", 
   "{"player":"lol","score":0}"]

Also in the player's html I keep individually the player and punctuation values to be able to modify them and then replace the previous object (this I also use in an if in case the player does not yet exist the score is 0 by default):

jugador =$('#txtplayer').val();
var player = jugador;
var score = 0;
localStorage.setItem("player",player);
localStorage.setItem("score",score);

And so I receive them in the html of the game:

var player = localStorage.getItem("player");
var score = localStorage.getItem("score");

Thank you in advance.

    
asked by Carlos Roberto Luna Ochoa 09.06.2018 в 17:51
source

2 answers

0

For security reasons, Javascript on the client side can not access system files.

The API Storage only allows to access or modify pairs of values stored by the browser itself. Yes you can store the data of the players, but in the browser, not in a file.

For more information: link

If it is mandatory that there is a JSON file in your project, you will need to use a server-side programming language (PHP, NodeJS ...).

    
answered by 09.06.2018 в 18:24
0

What I would do would be the following. The script can not be executed here because it does not let you play with the localstorage.

Greetings, I hope you find it useful

function addUser() {
  const userFromStorage = localStorage.getItem('players');
   // Si tengo jugadores los convierto en un array si no creo uno
  const USERS = userFromStorage ? JSON.parse(userFromStorage) : [] ;

  const user = document.getElementById('user_name');

  if(user && user.value) {
    
    const userExist = USERS.find( user => {
      return user.player === user.value;
    });
    // si el usuario no existe lo añado al array
    if(!userExist) {
      USERS.push({player:user.value,score:0 });
    }
    
    localStorage.setItem('players', JSON.stringify(USERS));
  } else {
    console.error('El jugador ya existe, escoja otro nombre');
  }

}


function updateScore(user, score) {
  const userFromStorage = localStorage.getItem('players');
  // Si tengo jugadores los convierto en un array si no creo uno
  const USERS = userFromStorage ? JSON.parse(userFromStorage) : [] ;
  if(USERS.length > 0){
    const userIndex = USERS.findIndex(
      u => {
       return u.player === user
      }
    );
    if (userIndex !== -1) {
      USERS[userIndex].score = score;
      // Añade el array al localstorage
      localStorage.setItem('players', JSON.stringify(USERS));
    } else {
      console.error('El usuario ${user} no existe en el array');
    }
  } else{
    console.error('no hay jugadores');
  }
} 

function updateUser() {
  const user = document.getElementById('user_name_update');
  const score = document.getElementById('user_score_update');
  updateScore(user.value, score.value);

}
<input type="text" id="user_name">

<button id="addUser" onclick="addUser()">Añadir usuario</button>
<hr>

<input type="text" id="user_name_update">
<input type="number" id="user_score_update">

<button id="updateUser" onclick="updateUser()">Modificar score del usuario</button>
    
answered by 10.06.2018 в 23:04