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

219
Visualizações
How to modify the value of only one of the keyvalues in the json array of js and keep the others?

This is the data that needs to be processed

let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "chl"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "chl"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "chl"
  }]

The requirement is to change only dn to ch the changed value is

  let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "ch"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "ch"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "ch"
  }]

This is the method I used

  test=test.map((item)=>({
    'id':item.id,
    'name':item.name,
    'dn':'ch'
  }))

This approach works but is not elegant because just to change one value you have to write the others as well, is there a better way to implement this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use rest syntax to collect the properties other than dn, then spread them into the new object.

const test=[{id:28620,name:"fenbi1",dn:"chl"},{id:5941,name:"fenbi2",dn:"chl"},{id:5226,name:"fenbi3",dn:"chl"}];

const output = test.map(({ dn, ...rest }) => ({ dn: 'ch', ...rest }));
console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

Just a simple for loop might be better than map in this situation

let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "chl"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "chl"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "chl"
  }]

  for (let item of test) {
     item.dn = 'ch'
  }

  console.log(test)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can write code like this.

let test=[
   {
      "id": 28620,
      "name": "fenbi1",
      "dn": "chl"
   },
   {
      "id": 5941,
      "name": "fenbi2",
      "dn": "chl"
   },
   {
      "id": 5226,
      "name": "fenbi3",
      "dn": "chl"
   }]

Now use array.map()

const newArray = test.map(e => ({...e,dn:"ch"}));
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