Overwrite Object

1

my question is this, I have an array with an object, and I do not know how to overwrite the value of the object I mean,

array = [
        usuario: 21312321,
        constraseña: "erica"
    },...]

What would interest me would be to edit the "erica", thank you very much. PS: I'm using Jquery

    
asked by Ricardo 22.06.2018 в 03:20
source

3 answers

2

I can not understand exactly what you mean (besides, your example lacks the start of the curve key { ).

But let's imagine that this is your array :

array = [
  {
    usuario: 21312321,
    contraseña: "erica",
  },
  {
    usuario: 12154156,
    contraseña: "1234",
  }
}

To access the password of your first user (both read and write) in the array would be any of these two lines:

array[0].contraseña = "paula"
console.log(array[0].contraseña)
array[0]["contraseña"] = "paula"
console.log(array[0]["contraseña"])

Let me know if this answer is useful or your question was different.

    
answered by 22.06.2018 / 03:31
source
1

You can do it this way

var data = [{
  name: 'Alfredo',
  age: 28
}]

console.log(data.name = "Beta")

As you can see inside the console.log() I access the name of the object and later to enter the value I do it as obj.clave and to assign a new value I do it with =nuevovalor

With the destructuring of objects in ES6 you can make it simpler look at this example

var data = {
  name: 'Alfredo',
  age: 28
}

var {name, age} = data

console.log(name = "jorge")
console.log(age = 89)
    
answered by 22.06.2018 в 03:38
0

I would do it in the following way:

let array = [
  {
    usuario: 21312321,
    constrasena: "erica"
  },
  {
    usuario: 1234,
    contrasena: "acire"
  }
]
// nuevaContrasena = nueva contraseña
//array = array a iterar
//usuario = usuario para la comparacion
function updateHash(nuevaContrasena, array, usuario) {

  array.forEach((elemento) => { // recoremos el elemento
    if (elemento.usuario == usuario) { // validamos el usuario al asignarle la contraseña
      elemento.contrasena = nuevaContrasena // modificamos la contraseña
    }
  })

}
console.log(array)
updateHash("nuevapass", array, 1234)
console.log(array)

so you know which user you are going to modify the password.

    
answered by 22.06.2018 в 18:36