简体   繁体   English

修改键值对Javascript中的字符串

[英]Amend strings in key-value pairs Javascript

I need to change all instances of a string within an array, I could do it like this, But is there not a more elegant solution when they are key value pairs? 我需要更改数组中字符串的所有实例,我可以这样做,但是当它们是键值对时,没有更好的解决方案吗?

var person = [];
person.push({
    name: 'John Smith',
    description: 'John Smith is tall.',
    details: 'John Smith has worked for us for 10 years.'
});
person.push({
    name: 'Michael Smith',
    description: 'Michael Smith is tall.',
    details: 'Michael Smith has worked for us for 10 years.'
});
person.push({
    name: 'Linda Smith',
    description: 'Linda Smith is tall.',
    details: 'Linda Smith has worked for us for 10 years.'
});

function replaceWordST() {
    var toReplace = "Smith";
    var replaceWith = "Jones";
    for (i = 0; i < person.length; i++) {
        person[i].name = person[i].name.replace(new RegExp(toReplace, 'g'), replaceWith);
        person[i].description = person[i].description.replace(new RegExp(toReplace, 'g'), replaceWith);
        // etcetc
    }
}

like an objet maybe: http://jsfiddle.net/mig1098/ekLmquap/ 像对象一样: http//jsfiddle.net/mig1098/ekLmquap/

var replace = {
        replaceWordST:function(person) {
            var toReplace = /Smith/g;
            var replaceWith = "Jones";
            jsonData = person;
            for(var obj in jsonData){
                    if(jsonData.hasOwnProperty(obj)){
                    for(var prop in jsonData[obj]){
                        if(jsonData[obj].hasOwnProperty(prop)){
                            jsonData[obj][prop] = replace.name(jsonData[obj][prop],toReplace,replaceWith);
                        }
                    }
                }
            }
            return jsonData;
        },
        name:function(name,toReplace,replaceWith){
            return name.replace(toReplace, replaceWith);
        }
}

a more elegant solution 更优雅的解决方案

You can reduce the number of similar lines by using a nested loop 您可以使用嵌套循环来减少相似行的数量

function replaceWordST() {
    var toReplace = "Smith",
        replaceWith = "Jones",
        re = new RegExp(toReplace, 'g'), // cache this!!
        keys = ['name', 'description', 'details' /*, etc*/],
        i, j; // don't forget to var these!!
    for (i = 0; i < theURLs.length; ++i) {
        for (j = 0; j < keys.length; ++j) {
            person[i][keys[j]] = person[i][keys[j]].replace(re, replaceWith);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM