0

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 🙏

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.