Edit values of a JSON object inside a Javascript array

0

I have a array of this type

my array = [{N:23/*editar el numero 23*/, k:5},{N:11, k:10},{N:89, k:66}]

And I want to change the number 23 to another number without affecting the rest of the object "k: 5"

I do not know what method or command I can use, because if I use the SPLICE method the whole object is updated and I only want to update the first data of the object without affecting the second one

    
asked by Michael Valdes Gonzalez 04.04.2018 в 15:24
source

2 answers

1

Simply assigning the value to that variable. You will have to place yourself in that position and then assign it.

var myarray = [{N:23/*editar el numero 23*/, k:5},{N:11, k:10},{N:89, k:66}];

// edito la variable 'myarray' dentro de 'N'
// y le asigno el valor "13"
myarray[0].N = 13;

Clarification:
[] = array
{} = object

To traverse an object in javascript you have two ways:

  • Inside square brackets: myObjeto["N"]
  • With a period followed by the key: myObjeto.N
  • answered by 04.04.2018 / 15:40
    source
    0

    Well I would do it like this:

    var my_array = [
      {N:23, k:5},
      {N:11, k:10},
      {N:89, k:66}
    ]
    
    function cambiarValor(valorABuscar, valorViejo, valorNuevo) {
      my_array.forEach(function (elemento) { // recorremos el array
      
         //asignamos el valor del elemento dependiendo del valor a buscar, validamos que el valor sea el mismo y se reemplaza con el nuevo. 
        elemento[valorABuscar] = elemento[valorABuscar] == valorViejo ? valorNuevo : elemento[valorABuscar]
      })
    }
    
    cambiarValor("N", 23, 30)
    console.log(my_array)
        
    answered by 04.04.2018 в 17:43