如何使用javascript向JSON数组添加属性
How to add attributes to JSON array using javascripts?
我想使用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);
}
相关文章:
- 向多维数组添加值和从多维数组请求值
- 如何将JS数组添加到Meteor自动表单条目中
- 在不使用循环的情况下,从一个数据库字符串值向javascript数组添加多个对象
- 将行从数组添加到谷歌图表
- 从不同的数组添加重复的图块 PIXI.js
- 如何在 Javascript 中向数组添加其他对象
- 将javascript数组添加到多维数组中
- Coderbyte数组添加解决方案--For循环与For循环
- Knockout.js向数组添加新项
- Highcharts将变量数组添加到序列中
- 向javascript对象数组添加值
- 我可以用Javascript向数组添加函数吗
- 将数组添加到另一个数组
- 你能给被劫持的JavaScript数组添加一个函数吗
- 我可以向数组添加对象键吗
- 如何向JSON数组添加新属性
- 通过将$resource查询数组添加到AngularJS中另一个数组的底部来进行分页加载
- 使用名称/值从 json 数组添加项
- Javascript数组添加 - 所有组合
- 从 json 文件向 javascript 数组添加值