如何将数据推送到JSON变量

时间:2012-03-20 12:57:27

标签: javascript json push

我有一个JSON变量,如下所示:

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]}

我需要使用javascript在每个事件中推送另一个属性,并使其如下所示:

{"events": [
{"event_id": "1", "event_name": "Breakfast", "event_type": "calendar"},
{"event_id": "1", "event_name": "Calling Bob", "event_type": "calendar"}
]}

3 个答案:

答案 0 :(得分:5)

如果你有

var obj = {"events": [....

然后只需使用

for (var i = 0; i < obj.events.length; ++i)
    obj.events[i].event_type = "calendar";

或优化:

for (var i = 0, len = obj.events.length; i < len; ++i)
    obj.events[i].event_type = "calendar";

答案 1 :(得分:3)

首先将其转换为Object

var obj = JSON.parse(theJSON);

for(var i = 0; i < obj.events.length; ++ i)
    obj.events[i].event_type = "calendar";

theJSON = JSON.stringify(obj);

答案 2 :(得分:1)

var yourJson = {"events": [
    {"event_id": "1", "event_name": "Breakfast"},
    {"event_id": "1", "event_name": "Calling Bob"}
]};

for(var eventKey in yourJson.events) {
    yourJson.events[eventKey]['event_type'] = 'calendar';
}