methuselah
methuselah

Reputation: 13216

Iterate over items in object, find matches and replace

I have an object returned in the following format:

[
    {
        "category": "Coach",
        "phrase_original": "Training {{the team}} to develop their match skills by ensuring they are comfortable with {{defence techniques}}",
        "phrase_filter": "Training {{group}} to develop their {{attribute}} skills by ensuring they are comfortable with {{factor}}"
    },
    {
        "category": "Coach",
        "phrase_original": "Assisting the {{fitness coach}} in strength and conditioning work to improve {{team performance}}",
        "phrase_filter": "Assisting the {{person}} in strength and conditioning work to improve {{factor}}"
    }
]

I would like to parse through each and replace:

What would be the best way of accomplishing this?

This is my code so far, I am not sure whether to implement the above. I am currently getting the data from the API endpoint, just not sure how to process it yet.

CategoryService.getCategoryDetail($scope.categoryId).then(function(dataResponse) {
  $scope.categoryDetail = dataResponse.data;
  angular.forEach($scope.categoryDetail, function(e) {
    // 1. find all the words in braces in phrase_filter
    // 2. replace them with html markup so they are rendered in the view differently   
    // e.phrase_filter = ???
  });
});

Upvotes: 1

Views: 53

Answers (1)

R. Foubert
R. Foubert

Reputation: 653

You can try something like that :

var inputs = [
  {
    "category": "Coach",
    "phrase_original": "Training {{the team}} to develop their match skills by ensuring they are comfortable with {{defence techniques}}",
    "phrase_filter": "Training {{group}} to develop their {{attribute}} skills by ensuring they are comfortable with {{factor}}"
  },
  {
    "category": "Coach",
    "phrase_original": "Assisting the {{fitness coach}} in strength and conditioning work to improve {{team performance}}",
    "phrase_filter": "Assisting the {{person}} in strength and conditioning work to improve {{factor}}"
  }
]

var replacers = {
  '{{group}}' : '<span style="group-button">group</span>',
  '{{attribute}}' : '<span style="attribute-button">attribute</span>',
  '{{factor}}' : '<span style="factor-button">factor</span>',
  '{{person}}' : '<span style="person-button">person</span>'
}

// Loop through every objects
inputs.forEach(function(input){
  Object.keys(replacers).forEach(function(key){
    // Replace every occurence of this key
    input['phrase_filter'] = input['phrase_filter'].replace(new RegExp(key, 'g'), replacers[key]);
  })
})

console.log(inputs);

But I'm not sure it's the best solution regardind the fact that you work with angular... You should create custom directives or something like that it would be more efficient ;) Hope it helps

Upvotes: 1

Related Questions