Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
Set nested property of json object using brackets notation in PUT request (svelte + strapi)

I'm using Svelte and Strapi for the project. Here is a simplified version of my problem:

The json where I want to send my PUT request. (localhost:1337/shapes/1)

{
  id: 1,
  name: 'square',
  colors: {
    red: false,
    blue: false,
    green: false
  }
}

The toggle buttons in svelte template:

{#each shapes as shape}
  <div on:click={toggleColor(shape, "red")}>red</div>
  <div on:click={toggleColor(shape, "blue")}>blue</div>
  <div on:click={toggleColor(shape, "green")}>green</div>
{/each}

The toggle function (see comments to find what's missing):

function toggleColor(shape, color) {
  let index = shapes.indexOf(shape);

  axios.put(`http://localhost:1337/shapes/${shape.id}`, {
    // How to write this part to toggle a color?
    // The commented code below doesn't work as it doesn't set a color without  
    // reseting others siblings
    // colors: {
    //   [color]: shape.colors[color] ? false : true
    // }
  })
  .then((res) => {
    coins[index].colors[color] = res.data.colors[color];
  })
  .catch((err) => {
    console.log(err.message)
  });
}

To understand more clearly what happens with this version, it returns this response if I click on blue button then red button:

{
  id: 1,
  name: 'square',
  colors: {
    red: true,
    blue: null,
    green: null
  }
}

Expected response:

{
  id: 1,
  name: 'square',
  colors: {
    red: true,
    blue: true,
    green: false
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You was almost there. The following code:

{
  colors: {
    [color]: shape.colors[color] ? false : true
  }
}

...will redefine colors as an object with only a single color in it. To also get the previous colors, use the spread syntax like:

{
  colors: {
    ...shape.colors,
    [color]: shape.colors[color] ? false : true
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda