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"
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]" .
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.
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);
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With