Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!