如何使用javascripts向JSON数组添加属性?

时间:2014-09-16 03:14:40

标签: javascript json arrays

我想使用Javascript动态构建以下JSON。

{    
    "Events": [{
        "Name": "Code Change",
        "Enabled": "true",
        "Properties": [{
            "Name": "url",
            "Value": "val"
        }]
    }],
    "Properties": [{
        "Name": "url",
        "Value": "val"
    }]    
} 

所以我编写了以下代码,但它创建了JSON对象,其中Name,Enabled和属性在单独的花括号下。无论如何要解决这个问题而不是使用push方法吗?

代码

var eventProperties="[{'Name':'url','Value':'val'}]";
var subscriptionProperties="[{'Name':'url','Value':'val'}]";

var eventArray = JSON.parse('[1, 5, "false"]');
var subArray = JSON.parse('[1, 5, "false"]');


var subscription = {
    Events: [],
    Properties: []
};

if(eventName != null && eventName != "") {
    subscription.Events.push({
        "Name" : eventName
    });
}

var index = 0;

if(eventEnabled != null && eventEnabled != "") {
    subscription.Events.push({
        Enabled: eventEnabled
    });
}

if(eventProperties != null && eventProperties != "") {
    subscription.Events.push({
        "Properties": eval('(' + eventProperties + ')')
    });
} 

if(subscriptionProperties != null && subscriptionProperties != "") {
    subscription.Properties = eval('(' + subscriptionProperties + ')');
}

输出

{    
    "Events": [{
        "Name": "Code Change"
     },
     {
        "Enabled": "true"
     },
     {
        "Properties": [{
            "Name": "url",
            "Value": "val"
        }]
     }],    
     "Properties": [{
         "Name": "url",
         "Value": "val"
     }]
} 

1 个答案:

答案 0 :(得分:1)

是的。您只需要创建一个这样的对象。

subscription.Events.push({
    Name: eventName,
    Enabled: eventEnabled,
    Properties: JSON.parse(eventProperties)
 });

或者使用当前流程:

 var subscription = {};

 var eventObject = {};

 if(eventName != null && eventName != "") {
     eventObject.Name = eventName;
 }

 if(eventEnabled != null && eventEnabled != "") {
     eventObject.Enabled = eventEnabled;
 }

 if(eventProperties != null && eventProperties != "") {
     eventObject.Properties = JSON.parse(eventProperties);
 }

 subscription.Events = [eventObject];

 if(subscriptionProperties != null && subscriptionProperties != "") {
     subscription.Properties = JSON.parse(subscriptionProperties);
 }