オブジェクトの配列があります:
const data = [
{
title: '"test1"',
excluded_dates: false,
},
{
title: '"test2"',
excluded_dates: [
{ excluded_date: "2020-09-12" },
{
excluded_date: "2020-09-17",
},
],
},
{
title: '"test3"',
excluded_dates: [
{
excluded_date: "2020-09-16",
},
{
excluded_date: "2020-09-24",
},
],
},
];
そして、exclude_dates配列に特定の日付(この例では2020-09-24)があるオブジェクトを削除して、次のように新しい配列を出力します。
outcome = [
{
title: '"test1"',
excluded_dates: false,
},
{
title: '"test2"',
excluded_dates: [
{ excluded_date: "2020-09-12" },
{
excluded_date: "2020-09-17",
},
],
}
];
このため、私は二重フィルタリングの使用を考えていました。私もsome()を試しましたが、これはオブジェクトの配列ではなく配列用です。
const outcome = data.filter(function (event) {
if (event.excluded_dates) {
return event.excluded_dates.filter(
(date) => date.excluded_date === "2020-09-24"
);
}
});
console.log(outcome);
このコースは期待どおりに動作しません。ここで何が欠けていますか?
true
オブジェクトにexcluded_dates
プロパティがない場合は必ず返してください。また、探している日付は1つだけなので、2番目の使用Array.prototype.filter
をArray.prototype.some()
const outcome = data.filter((event) => {
return !(
event.excluded_dates && // if there is no `excluded_dates` property, return `true`
event.excluded_dates.some( // otherwise, try to find the date. if found, return `false`
({ excluded_date }) => excluded_date === "2020-09-24"
)
);
});
コードスニペットの例:
const data = [{
title: '"test1"',
excluded_dates: false,
},
{
title: '"test2"',
excluded_dates: [{
excluded_date: "2020-09-12"
},
{
excluded_date: "2020-09-17",
},
],
},
{
title: '"test3"',
excluded_dates: [{
excluded_date: "2020-09-16",
},
{
excluded_date: "2020-09-24",
},
],
},
];
const outcome = data.filter((event) => {
return !(
event.excluded_dates &&
event.excluded_dates.some(
({ excluded_date }) => excluded_date === "2020-09-24"
)
);
});
console.log(outcome);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加