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

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

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 Relatório

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 Relatório

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