gpt4 book ai didi

javascript - 扫描嵌套对象的数组以查找匹配项

转载 作者:行者123 更新时间:2023-12-01 03:50:50 24 4
gpt4 key购买 nike

我有一个看起来像这样的对象 -

{
"Campaigns":
{
"Campaign1":
{
"reports":
[
{
"month": "Google - January - Monthly Report.csv",
"impressions": 53,
"clicks": 31,
"cost": 18
},
{
"month": "Google - April - Monthly Report.csv",
"impressions": 13,
"clicks": 11,
"cost": 8
}
]
},
"Campaign2":
{
"reports":
[
{
"month": "Google - March - Monthly Report.csv",
"impressions": 13,
"clicks": 11,
"cost": 8
}
]
}
}

}

我有一个带有文件名的附加数组..让我们以这个数组为例 -

reports_array = [
'Google - January - Monthly Report.csv',
'Google - February - Monthly Report.csv',
'Google - March - Monthly Report.csv',
'Google - April - Monthly Report.csv'
]

我希望完成的是扫描每个广告系列(在本例中为“广告系列1”和“广告系列2”)中的“缺失”报告,并推送所有属性(展示次数、点击次数、成本)均为零的新报告,因此,campaign1 除了 1 月和 4 月的报告外,还将有 2 月和 3 月的报告,只是用零而不是真实数据。 Campaign2 将有另外三个报告(一月、二月和四月),也用零代替真实数据。

到目前为止我尝试过的(没有取得多大成功)-

reports_array.forEach(function(arr_report) {
for(let campaign in campaigns) {
if(campaigns[campaign].hasOwnPropert('reports')) {
campaigns[campaign].reports.forEach(function(report) {
if(report.month !== arr_report) {
console.log('campaign '+campaign+' is missing '+arr_report);
campaigns[campaign].reports.push({
month: arr_report,
impressions: 0,
clicks: 0,
cost: 0
});
}
});
}
}
});

最佳答案

这是一种方法:

var campaigns = campaigns_object.Campaigns;

Object.keys(campaigns)
.forEach(function(campaign) {
reports_array.forEach(function(report, index) {
var has_report = campaigns[campaign].reports.some(function(campaign_report) {
return (campaign_report.month === report);
});

if (!has_report) {
campaigns[campaign].reports.splice(index, 0, {
month: report,
impressions: 0,
clicks: 0,
cost: 0
});
}
});
});

console.log(campaigns);

这会给你这个结果:

{
"Campaign1": {
"reports": [
{
"month": "Google - January - Monthly Report.csv",
"impressions": 53,
"clicks": 31,
"cost": 18
},
{
"month": "Google - February - Monthly Report.csv",
"impressions": 0,
"clicks": 0,
"cost": 0
},
{
"month": "Google - March - Monthly Report.csv",
"impressions": 0,
"clicks": 0,
"cost": 0
},
{
"month": "Google - April - Monthly Report.csv",
"impressions": 13,
"clicks": 11,
"cost": 8
}
]
},
"Campaign2": {
"reports": [
{
"month": "Google - January - Monthly Report.csv",
"impressions": 0,
"clicks": 0,
"cost": 0
},
{
"month": "Google - February - Monthly Report.csv",
"impressions": 0,
"clicks": 0,
"cost": 0
},
{
"month": "Google - March - Monthly Report.csv",
"impressions": 13,
"clicks": 11,
"cost": 8
},
{
"month": "Google - April - Monthly Report.csv",
"impressions": 0,
"clicks": 0,
"cost": 0
}
]
}
}

JSFiddle 演示:https://jsfiddle.net/wfya0ycs/3/

关于javascript - 扫描嵌套对象的数组以查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219468/

24 4 0
文章推荐: PHP Jquery ajax 类
文章推荐: python - 如何使用 python-twitter 删除所有推文?
文章推荐: jquery - 如何将 Jquery
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com