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

152
Views
Put dynamic value inside a object value string

I am new to JS and trying to get values from an array of objects.

var jsonData = [{
    "role": "abc",
    "nextrole": "def",
    "goals": {
        "goal1": "goal 1",
        "goal2": "goal 2",
        "goal3": "goal `${a}`"
    }
  },
  {
    "role": "def",
    "nextrole": "ghi",
    "goals": {
        "goal1": "goal 4",
        "goal2": "goal 5",
        "goal3": "goal `${a}`"
    }
  },
  {
    "role": "ghi",
    "nextrole": "jkl",
    "goals": {
        "goal1": "goal 7",
        "goal2": "goal 8",
        "goal3": "goal `${a}`"
    }
 }];

var result2 = jsonData.find(obj => {
  return obj.role === "def"
});
var a = "any String";
Object.keys(result2.goals).forEach(function(key) {
  $('ul').append(`<li>${result2.goals[key]}</li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2></h2>
<ul></ul>

As you can see in the example given I am able to get the object based on the role defined. but how to insert a dynamic value or any other variable value inside the goal 3, ${a}; if this is not the right way to do it, please suggest me a better way. I am not able to find a way to do it. any help would be apricated.

Thanks

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can have the values as functions that can accept a param and return string:

const jsonData = [
  {
    "role": "abc",
    "nextrole": "def",
    "goals": {
        "goal1": () =>  "goal 1",
        "goal2": () =>  "goal 2",
        "goal3": (a) => `goal ${a}`
    }
  },
  {
    "role": "def",
    "nextrole": "ghi",
    "goals": {
        "goal1": () =>  "goal 4",
        "goal2": () =>  "goal 5",
        "goal3": (a) => `goal ${a}`
    }
  },
  {
    "role": "ghi",
    "nextrole": "jkl",
    "goals": {
        "goal1": () =>  "goal 7",
        "goal2": () =>  "goal 8",
        "goal3": (a) => `goal ${a}`
    }
  }
];

const result2 = jsonData.find(({ role }) => role === "def");
const a = "any String";

Object.keys(result2.goals).forEach(key => {
  $('ul').append(`<li>${result2.goals[key](a)}</li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2></h2>
<ul></ul>

about 4 years ago · Santiago Trujillo 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!