在Javascript对象中查找和替换值

时间:2013-07-18 13:29:48

标签: javascript jquery replace

我有以下javascript对象。在这个对象上,我想执行查找和替换操作。我想仅替换第二列的值。我想将XXXX和'数据'替换为{total'替换DDDD。执行此操作的最有效方法是什么。

{
    "Result": [
        [
            "1",
            "Total",
            "Franchise",
            "5,491,396,782",
            "2,691,451,027"
        ],
        [
            "2",
            "Total",
            "Growth",
            "68,727,420",
            "45,152,969"
        ],
        [
            "3",
            "Total",
            "Research",
            "3,970,296,773",
            "1,921,277,988"
        ],
        [
            "4",
            "Data",
            "Franchise",
            "4,793,487,319",
            "2,347,241,939"
        ],
        [
            "5",
            "Data",
            "Growth",
            "65,353,557",
            "40,817,844"
        ],
        [
            "6",
            "Data",
            "Research",
            "3,411,890,959",
            "1,644,610,206"
        ]
    ]
}

谢谢

2 个答案:

答案 0 :(得分:1)

for(var i=0; i<result.length; i++)
    if(result[i].length >= 2)
        result[i][1] = result[i][1].replace(/^Total$/, "xxxx").replace(/^Data$/, "DDDD");

答案 1 :(得分:0)

迭代,迭代,迭代

for (key in obj) {
    for (var i=0; i<obj[key].length; i++) {
        for (var j=0; j<obj[key][i].length; j++) {
            if (obj[key][i][j] == 'Total') obj[key][i][j] = 'XXXX';
            if (obj[key][i][j] == 'Data') obj[key][i][j] = 'DDDD';
        }
    }
}

FIDDLE