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

How to add attributes to JSON array using javascripts?

本文关键字:数组 添加 属性 JSON 何使用 javascript      更新时间:2023-09-26

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

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

所以我写了以下代码,但它创建了JSON对象,其中Name、Enabled和properties位于单独的花括号下。有没有办法解决这个问题,而不是使用推送方法?

代码

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"
     }]
} 

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

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);
 }