new_coder
new_coder

Reputation: 33

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

Upvotes: 3

Views: 1042

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

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>

Upvotes: 2

Related Questions