0

我有以下 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 块

4

2 回答 2

1

由于您的 jsonCoordinates 不是数组,因此当您执行 each 时,它不会执行。我认为如果您将其包装在 []; 周围,您的代码会起作用。

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);
于 2013-05-03T15:16:36.390 回答
1

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

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

http://jsfiddle.net/XSzYM/

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

于 2013-05-03T15:17:20.230 回答