Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace keys in string by value based on key–value entries in object

I’m trying to convert each integer in a string to its corresponding value in an object based on its key–value entries. For example if I have:

var arr = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
  };
var str = "I want value 3 here and value 234 here";

I would expext the output to be:

new_str = "I want value_three here and value other_value here"
like image 919
adamK Avatar asked Jun 26 '12 01:06

adamK


People also ask

Does object keys convert to string?

If your key isn't a string, JavaScript will convert it to a string when you use it as a property name. Note that if you didn't provide a toString , the keys would have been the string "[object Object]" .

How do you reverse the key and value of an object?

invert() method of “underscore. js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys.


2 Answers

I'm just doing this off the top of my head, but this should work.

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(key, arr[key]);
}

If you wanted all occurrences of the number to be replaced, you'd need to incorporate a Regex into the mix:

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(new RegExp(key, "g"), arr[key]);
}

Also, I'd pick another name other than arr, as that implies it's an array when it's clearly an object. Also, make sure you only use for-in loops on objects, not arrays, because of issues with prototype leakage and others.

You can also do this with jQuery, but it's probably overkill:

var new_str = str;

$.each(arr, function (key, value) {
    new_str = new_str.replace(key, value);
});
like image 153
Eli Avatar answered Sep 24 '22 02:09

Eli


Suppose you have an object like arr, with str defined and new_str declared. Then, assuming that we aim for a general solution the following works:

var arr = { "3": "value_three", "6": "value_six", "234": "other_value" };
var str = "I want value 3 here and value 234 here";

// Building a regex like `/3|6|234/g`
let re = new RegExp(Object.keys(arr).join('|'), 'g');

// Arrow function is approximately equivalent to
// an anonymous function like `function(match) { return arr[match]; }`
new_str = str.replace(re, match => arr[match]);

console.log(new_str);

Just as a little side note, arr given your example is an Object. (I realize that they are sometimes called associative arrays as well; just pointing it out).

like image 30
YenForYang Avatar answered Sep 25 '22 02:09

YenForYang