Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda