我在将数组中的JSON对象组合在一起时遇到了困难。本质上,我正在创建一个新的空白数组(A),遍历现有的JSON数组(B),检查A是否包含B中已存在属性的对象,如果没有,则创建一个新对象并将其推送到甲
这就是我的尝试:
var grouped_requests = groupByProperty(campaign_requests, "send_date");
function groupByProperty(data, property) {
var result = [];
$.each(data, function(index, item) {
var group;
if ($.inArray(item[property], result)==-1) {
// create a new group
group = new Object();
// set the group's properties
group.deadline = item.deadline;
group.send_date = item.send_date;
group.description = item.description
group.action = $('<button />', {
class: "btn btn-primary",
text: "Preview"
}).attr('data-toggle', 'modal').attr('data-target', '#modal_request').attr('data-ids', data.map(function(m) {if (m.property = item.property) {return m}}).join(';')).prop('outerHTML');
result.push(group);
}
});
return result;
}
我遇到问题的地方是双重的。首先,$ .inArray不能准确地检查A是否包含参数中B中存在参数的对象。其次,data-id的data.map返回空值;例如如果有两个相同的属性,则返回;
。
更新
以下是我收到的一些示例数据:
[{
"campaign_queue_id": "1",
"email_id": "98",
"subject": "Test1",
"body": "Test1",
"deadline": "June 17th,2018",
"send_date": "June 17th, 2018",
"description": "Customer"
}, {
"campaign_queue_id": "2",
"email_id": "22",
"subject": "Test2",
"body": "Test2",
"deadline": "June 17th,2018",
"send_date": "June 17th, 2018",
"description": "Customer"
}, {
"campaign_queue_id": "3",
"email_id": "77",
"subject": "Test3",
"body": "Test3",
"deadline": "June 20th,2018",
"send_date": "June 25th, 2018",
"description": "Center of Influence"
}, {
"campaign_queue_id": "4",
"email_id": "5",
"subject": "Test4",
"body": "Test4",
"deadline": "June 20th,2018",
"send_date": "June 25th, 2018",
"description": "Center of Influence"
}]
这就是我想要“分组”JSON数据的方式:
[{
"deadline": "June 17th,2018",
"send_date": "June 17th,2018",
"description": "Customer",
"action": "<button class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#modal_request\" data-ids=\"1;2\">Preview</button>"
},
{
"deadline": "June 20th,2018",
"send_date": "June 25th,2018",
"description": "Customer",
"action": "<button class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#modal_request\" data-ids=\"3;4\">Preview</button>"
}]
答案 0 :(得分:0)
通过使用以下代码,我能够实现我想要做的事情:
var send_dates = $.unique($.map(data, function(campaign) {
return campaign.send_date;
}));
var campaigns = [];
$.each(send_dates, function(key, value) {
var groups = $.grep(data, function(campaign) {
return campaign.send_date === value;
});
var ids = $.map(groups, function(campaign) {
return campaign.campaign_queue_id;
});
// create a new group
var group = new Object();
// set the group's properties
group.deadline = groups[0].deadline;
group.send_date = groups[0].send_date;
group.description = groups[0].description;
group.action = $('<button />', {
class: 'btn btn-primary',
text: 'Preview'
}).attr('data-toggle', 'modal').attr('data-target', '#modal_request').attr('data-ids', ids.join(';')).prop('outerHTML');
// add the group to the array
campaigns.push(group);
});
但是,如果有更有效的方法,我愿意接受建议。