我有一个对象数组,每个元素看起来像这样:
DF.write
.mode(SaveMode.Overwrite)
.option("timestampFormat", "yyyy-MM-dd HH:mm")
在每个元素中都有一个提交对象数组,它们看起来像这样:
2017-02-20 06:53
唯一需要注意的属性是addAt值。 我想根据日期范围过滤出提交对象。到目前为止,这是我一直没有尝试过的方法:
campaigns: (5) ["get.dentalintel.net/call-insight-DeshaunWatson", "get.dentalintel.net/practice-analysis-DeshaunWatson", "get.dentalintel.net/morning-huddle-DeshaunWatson", "get.dentalintel.net/new-morning-huddle-DeshaunWatson", "get.dentalintel.net/followups-DeshaunWatson"]
email: "dwats@gmail.com"
name: "Deshaun Watson"
submissions: [{…}]
user_id: 166
它将删除一些提交对象,但不会删除正确的对象。任何关于更好方法的建议将不胜感激。
答案 0 :(得分:1)
要进行过滤,请使用Array.filter
。这将返回一个新数组,该数组仅具有满足boolean
返回的callback
的值。要从现有阵列创建新阵列,请使用Array.map
而不是Array.forEach
。 forEach循环仅迭代这些值,但是Array.map
为每个元素返回一个修改后的值或新值。
const filterByDate = () => {
const { partners, endDate, startDate } = this.state;
const filteredPartners = partners.map(partner => {
return {
...partner,
submissions: partner.submissions.filter(submission =>
moment(submission.addedAt).isBetween(startDate, endDate)
)
};
});
};
Array.filter和Array.map示例(无突变)
const testArray = [{
id: 1
}, {
id: 2
}, {
id: 3
}, {
id: 4
}]
const filtered = testArray.filter(e => e.id !== 3)
const mapped = testArray.map(e => {
return {
id: e.id,
name: `Name of ${e.id}`
}
})
console.log("Test Array: ", testArray)
console.log("Filtered Array: ", filtered)
console.log("Mapped Array: ", mapped)
答案 1 :(得分:0)
您可以在此用例中使用Array.prototype.filter()
filterByDate = () => {
const { partners, endDate, startDate } = this.state;
partners.forEach(partner => {
partner.submissions = partner.submissions.filter(sub => moment(partner.submissions[i].addedAt).isBetween(startDate, endDate));
});
};