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

199
Visualizações
Modifying a specific value in a nested object (JavaScript)

I got this type of object:

const obj = {
    group: {
        data: {
            data: [
                {
                    id: null,
                    value: 'someValue',
                    data: 'someData'
                }
            ]
        }
    }
};

I need to edit this object so whenever null is in the property value, it would be replaced with some string.

Meaning if the replacement string will be 'someId', the expected outcome is:

const obj = {
    group: {
        data: {
            data: [
                {
                    id: 'someId',
                    value: 'someValue',
                    data: 'someData'
                }
            ]
        }
    }
};

Closest I found were this and this but didn't manage to manipulate the solutions there to what i need.

How should I do it?

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

0

Probably running into issues with the array values. Pass in the index of the array to modify. In this case [0]

obj.group.data.data[0].id = "someId"

EDIT This will update all null values of id inside the data array:

obj.group.data.data.forEach(o => {
  if (o.id === null) {
    o.id = "someId"
  }
})

Another EDIT

Here is an algorithm to recursively check all deeply nested values in an object. It will compile an array of object paths where null values live. There is an included helper method to find and update the value of the object at the given path in the array. There is a demonstration of the program in the console.

const object = {
  group: {
    data: {
      data: [
        {
          id: null,
          value: "foo",
          data: [null, "bar", [null, { stuff: null }]]
        },
        {
          id: null,
          value: null,
          data: {
            bar: [null]
          }
        },
        {
          id: null,
          value: "foo",
          data: null
        },
        {
          id: 4,
          value: "foo",
          data: "bar"
        },
        {
          id: 4,
          value: "stuff",
          data: null
        }
      ]
    },
    attributes: null,
    errors: ["stuff", null]
  }
}

const inspectProperty = (key, obj, path = "") => {
  if (typeof obj[key] === "object") {
    if (obj[key] instanceof Array) {
      return analyzeArray(obj[key], `${path ? path + "." : ""}${key}`);
    }
    return analyzeObj(obj[key], `${path ? path + "." : ""}${key}`);
  }
  return [];
};

const analyzeKey = (obj, key, path = "") => {
  if (obj[key] === null) return [`${path ? path + "." : ""}${key}`];
  return inspectProperty(key, obj, path).reduce((a, k) => [...a, ...k], []);
};

const analyzeObj = (obj, path = "") => {
  return Object.keys(obj).map((item) => analyzeKey(obj, item, path));
};

const analyzeArray = (array, path) => {
  return array.map((item, i) => analyzeKey(array, i, path));
};

const updateNullValue = (path, value) => {
  let p = path.split(".");
  p.reduce((accum, iter, i) => {
    if (i === p.length - 1) {
      accum[iter] = value;
      return object;
    }
    return accum[iter];
  }, object);
};

let nullValues = analyzeObj(object)[0]

console.log(nullValues)

nullValues.forEach((nullVal, i) => {
  updateNullValue(nullVal, "hello-" + i)
})

console.log(object)

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