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

143
Vistas
Replace value of nested object with variable structure

I've an object like this:

const obj = {a: {x: 0, y: 0}}

that could be also:

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

So, the obj can have more than one key and with variables key names. I need to replace each x value with a a string like this ${x}% so the x value + the percentage symbol.

How can I do that?

The expected results should be:

const obj = {a: {x: 0, y: 0}} // {a: {x: '0%', y: 0}}
const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}} // {a: {x: '0%', y: 0}, b: {x: '10%', y: 3}, abcd: {x: '-1%', y: 0}}

I tried looping the object but I don't know if there is a smartest solution

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

let result = Object.fromEntries(Object.entries(obj).map(([k,v]) => {
    return [k,{...v,x:`${v.x}%`}]
}))

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can also check the object recursively. So no matter how deep the object goes every given key that matches gets a suffix.

I also make sure to create a copy of the object to prevent altering the original object(s).

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}};

const addSuffixToObj = (obj, key, suffix) => {
  const copy = {...obj};

  Object.keys(copy).forEach((prop) => {
    if (typeof copy[prop] === 'object') {
      copy[prop] = addSuffixToObj(copy[prop], key, suffix);
    }else if(prop === key){
      copy[prop] = copy[prop] + suffix;
    }
  });
  
  return copy;
}

// Add "%" to all "x" keys
const result = addSuffixToObj(obj, 'x', '%');

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can get the array of object keys and then use forEach, it's a method that executes provided function for every element of array(here - for every object key):

Object.keys(obj).forEach(el => obj[el].x = `${obj[el].x}%`)
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