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

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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