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

213
Visualizações
Javascript: How to update a nested json, given the key PATH like doc.field1.field2 as string

I am trying to update a nested JSON which is given as an input, e.g.:

{
    "doc": {
        "a1": {
            "b1": 1,
            "b2": [
                "one",
                "two"
            ]
        },
        "a2": "xyz"
    }
}

The JSON structure is not known.

Field to update is an input string eg: "doc.a2" or "doc.a1.b1" or "doc.a1.b2"

In addition to the path, the old value and a new value is also given as input. If the value in the path matches the old value, I want to update it with new value.


I tried with eval() and seems possible like if path is "doc.a1.b1", then eval(doc['a1']['b1']='new value');

But using eval may lead to security issues. Is there a better way to achieve this?

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

0

Don't reinvent the wheel - lodash's set can do this for you:

_.set(objToUpdate, 'doc.a1.b1', 'new_value');
about 4 years ago · Juan Pablo Isaza Relatório

0

try this

var input1 = "doc.a2";
val1 = "val1";

updateVal(obj, input1, val1);
console.log("val1", obj);

function updateVal(obj, input, val) {
  let props = input.split(".");
  let currObj = obj;
  let index = 0;
  for (index = 0; index < props.length - 1; index++) {
    currObj = currObj[props[index]];
  };
  currObj[props[index]] = val;
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming you don't want to rely on a third party library, here is a 5-line proposal (it may need refinement to tackle corner cases such as invalid given path, depending on how you want to handle those cases, e.g. error, or create the path).

// given: ///////////////////////////////////

const obj = {
    "doc": {
        "a1": {
            "b1": 1,
            "b2": [
                "one",
                "two"
            ]
        },
        "a2": "xyz"
    }
}
const str = "doc.a1.b2"
const newValue = ["three"]

// do: ///////////////////////////////////////

const keys = str.split(".")
let ptr = obj
while(keys.length>1)
    ptr = ptr[keys.shift()]
ptr[keys.shift()] = newValue

// result:  ///////////////////////////////////

console.log(obj)

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