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

313
Visualizações
How to use path variable in JSON path

I'm trying to use a path variable in a JSON path.

My problem is that my variable is added as a new key to the JSON object instead of replacing my path.

My Example Code

Data = {
    first:{
        "Name":"John",
        "Age":"43"
    }
}

let path = "first.name"
let value = "Jan"

Data[path] = value
console.log(Data)

Current Output

Data = {
    first:{
        "Name":"John",
        "Age":"43"
    },
    "first.name": "Jan",
}

Expected Output

Data = {
    first:{
        "Name":"Jan",
        "Age":"43"
    }  
}

Is there a way to solve this? Thanks for your help 🙏

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

0

This script shall do what you want with an object (if I understood your problem well), until you provide it with the correct path :-)

function setAttr(obj, path, value){
    let objCopy = obj;
    let attrNameArr = path.split('.');
    for(let idx = 0; idx < attrNameArr.length-1; idx++){
        objCopy = objCopy[attrNameArr[idx]];
    }
    objCopy[attrNameArr[attrNameArr.length-1]] = value;
    return obj;
}


Data = {
    first:{
        "Name":"John",
        "Age":"43"
    }
}

setAttr(Data, "first.Name", "Jan");
console.log(Data);

it basically changes the attributes of object using the fact that objCopy and obj share the same reference.

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