修改键值对Javascript中的字符串

时间:2014-12-30 13:58:08

标签: javascript arrays json string

我需要更改数组中字符串的所有实例,我可以这样做,但是当它们是键值对时,是不是更优雅的解决方案?

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
    }
}

2 个答案:

答案 0 :(得分:2)

像对象一样: 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);
        }
}

答案 1 :(得分:0)

  

更优雅的解决方案

您可以使用嵌套循环

来减少相似行的数量
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);
        }
    }
}