0

I have code

let letters = [
 {"ae": "a"},
 {"ac": "c"}
];

String.prototype.swapLetters = function(){ 
    return this.replace(/ae/g, 'a').replace(/ac/g, 'c');
}

var decLetter= new String(response[i].name).swapLetters();

How can I use my prototype function with JSON object values? JSON will be generated dynamically.

3
  • 1
    You could use JSON.stringify, call your function, then use JSON.parse to change it back into an object. It entirely depends on what you want to do, your question is very vague Commented Oct 29, 2019 at 15:01
  • I just want to swap letters for string. I have input when I type a response should be a. When I type ae response also should be a. It's like accent folding for autocomplete Commented Oct 29, 2019 at 15:05
  • 1
    I see no JSON data here. letters is an array of objects. JSON is a text format. Commented Oct 29, 2019 at 15:24

1 Answer 1

1

Iterate over the array and apply the function to each one:

String.prototype.swapLetters = function() {
    let result = this;
    letters.forEach(pair => {
      const key = Object.keys(pair)[0];
      const value = pair[key];
      result = result.replace(key, value);
    });
    return result;
}

Of course, if you refactor your data, you can make this much simpler:

let letters = {
    "ae": "a",
    "ac": "c"
};

String.prototype.swapLetters = function() {
    return Object.keys(letters).reduce((result, replacer) => {
        return result.replace(replacer, letters[replacer]);
    }, this);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is what I'm looking for!

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.