迭代嵌套的JSON数组并更改属性的值

时间:2013-05-03 15:12:02

标签: javascript jquery json client-side

我有以下JSON对象

{
    "class": "go.GraphLinksModel",
        "nodeDataArray": [{
        "key": "CTR:2",
            "type": "Controller",
            "devicename": "ACU-1K",
            "deviceid": "2",
            "imageUrl": "http://localhost:52233/Images/ComputerSpeaker_32.png",
            "loc": "280 112"
    }, {
        "key": "CTR:1",
            "type": "Controller",
            "devicename": "C302-1",
            "deviceid": "1",
            "imageUrl": "http://localhost:52233/Images/ComputerSpeaker_32.png",
            "loc": "477 92"
    }, {
        "key": "RDR:25",
            "type": "Reader",
            "devicename": "1K-1-RDR01",
            "deviceid": "25",
            "imageUrl": "http://localhost:52233/Images/Plugin_32.png",
            "loc": "592 41"
    }],
        "linkDataArray": []
}

我想遍历nodeDataArray,并为nodeDataArray中的每个项更改imageUrl的值

我试过了,但它没有用

$.each(jsonCoordinates, function(key, value) {
    var nodeData = value.nodeDataArray;
    $.each(nodeData, function(k, v) {
        v.imageUrl = "default";
    });

});

应该怎么做?

jsonCoordinates包含上面的整个JSON块

2 个答案:

答案 0 :(得分:1)

由于你的jsonCoordinates不是一个数组,当你执行每个数组时它都不会执行。我认为如果你将它包装在[];

中,你的代码就可以了

http://jsfiddle.net/Xu9gH/1/

var Data = {"class":"go.GraphLinksModel","nodeDataArray":[{"key":"CTR:2","type":"Controller","devicename":"ACU-1K","deviceid":"2","imageUrl":"http://localhost:52233/Images/ComputerSpeaker_32.png","loc":"280 112"},
{"key":"CTR:1","type":"Controller","devicename":"C302-1","deviceid":"1","imageUrl":"http://localhost:52233/Images/ComputerSpeaker_32.png","loc":"477 92"},
{"key":"RDR:25","type":"Reader","devicename":"1K-1-RDR01","deviceid":"25","imageUrl":"http://localhost:52233/Images/Plugin_32.png","loc":"592 41"}],
"linkDataArray":[]};

$.each(Data.nodeDataArray, function(k, v) {
 v.imageUrl = "default";
});

console.log(Data);

答案 1 :(得分:1)

您不需要嵌套的$.each方法,直接遍历nodeDataArray

$.each(jsonCoordinates.nodeDataArray, function(index, value) {
    value.imageUrl = "default";
});

http://jsfiddle.net/XSzYM/

建议:始终使用console.log()来调试代码,特别是迭代嵌套对象和数组。