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

118
Visualizações
Filter an object in Javascript

I want to change an object key with another, depending by condition.

const obj = {
  name: 'carl',
  age: 2
};

const filterF = (obj, toChange, newV) => {
  return Object.keys(obj).reduce((acc, key) => {
    if (obj[key] === toChange) {
      acc[key] = newV;
    }
    return acc
  }, {})
}


console.log(filterF(obj, 'name', 'newName'))

Basically i expect this:

{
  name: 'newName',
  age: 2
};

Running my code i get an empty object. How to fix the code?

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

0

You only need to add or update the value

const obj = {
  name: 'carl',
  age: 2
};

const addOrUpdate= (obj, key, value) => { 
// no need to itterate
  obj[key] = value;
return obj
}


console.log(addOrUpdate(obj, 'name', 'newName'))

If you only need to update the value if its key already exists in object.

const obj = {
  name: 'carl',
  age: 2
};

const update= (obj, key, value) => { 
// no need to itterate
  if(obj.hasOwnProperty(key)) {
    obj[key] = value;
   }
return obj
}


console.log(update(obj, 'name', 'newName'))

// no new value added
console.log(update(obj, 'city', 'my city'))

If you just want to know how to achieve this with reduce for leaning purpose only.

you should not use reduce here since you are just creating a shallow copy of the previous object, but just for learning purpose i have added an example and where you went wrong.

const obj = {
  name: 'carl',
  age: 2
};

const filterF = (obj, toChange, newV) => {
  return Object.keys(obj).reduce((acc, key) => {
     // you had key wronly written as keys, and comparing objectp[key] value with new key
  if (key === toChange) {
      acc[key] = newV;
    } else {
      acc[key] = obj[key];
    }
    return acc
  }, {})
}


console.log(filterF(obj, 'name', 'newName'))

about 4 years ago · Juan Pablo Isaza Relatório

0

You should apply the changes by assigning a config to the original object.

This will allow you to change many properties at once.

const
  obj = { name: 'carl', age: 2 },
  alter = (obj, config) => Object.assign(obj, config); // or { ...obj, ...config }

console.log(alter(obj, { name: 'newName' }))

If you really want to split-out the key and value as separate params, you could try this instead:

const
  obj = { name: 'carl', age: 2 },
  alter = (obj, key, value) => Object.assign(obj, { [key]: value });

console.log(alter(obj, 'name', 'newName'))

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