Search code examples
javascriptjsonvariablespath

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 🙏


Solution

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