簡體   English   中英

Javascript 嵌套數組和過濾器

[英]Javascript nested array and filter

這是我的代碼

https://codepen.io/hobbesa/pen/jOGREKy?editors=1111

我試圖獲得僅工作日的價格。我該怎么做?

 this.getPriceWeekDay = this.StrategypricingDetail.map((rec) => rec.map((daysOfWeek) => { return daysOfWeek; }),

您可以首先使用filterfind方法過濾不包含SaturdaySunday的項目,然后通過map方法迭代過濾列表以僅提取價格屬性,如下所示:

 let StrategypricingDetail = [ { id: 3, name: "test", price: 30, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" }, { id: 3, name: "Wednesday" } ] }, { id: 23, name: "Testing2", price: 10, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" } ] }, { id: 13, name: "Testing3", price: 14, daysOfWeek: [ { id: 1, name: "Saturaday" }, { id: 2, name: "Sunday" } ] } ]; const weekDaysPrice = StrategypricingDetail.filter(({daysOfWeek}) =>.daysOfWeek.find(({name}) => name == 'Saturaday' || name == 'Sunday'));map(({price}) => price). console;log(weekDaysPrice);

您可以在下面使用一種解決方案。

 let strategypricingDetail = [ { id: 3, name: "test", price: 30, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" }, { id: 3, name: "Wednesday" } ] }, { id: 23, name: "Testing2", price: 10, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" } ] }, { id: 13, name: "Testing3", price: 14, daysOfWeek: [ { id: 1, name: "Saturaday" }, { id: 2, name: "Sunday" } ] } ]; let finalList = []; // Create list of eligible days for the search let daysToInclude = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ]; strategypricingDetail.forEach((item, index) => { for (let i = 0; i < item.daysOfWeek.length; i++) { // Check if the day is in the eligible list if (daysToInclude.includes(item.daysOfWeek[i].name)) { finalList.push(item); break; // When found, break out of the search after adding it to the final list. } } }); console.log(finalList)

在此解決方案中,您遍歷可用項目,然后將每個項目的“daysOfWeel”列表與符合條件的日期列表進行比較。 一旦找到,它就會停止搜索,並將該項目添加到新列表中,直到您以適當日期的列表結束。

 //StrategypricingDetail is the whole json const StrategypricingDetail = [ { id: 3, name: "test", price: 30, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" }, { id: 3, name: "Wednesday" } ] }, { id: 23, name: "Testing2", price: 10, daysOfWeek: [ { id: 1, name: "Monday" }, { id: 2, name: "Tuesday" } ] }, { id: 13, name: "Testing3", price: 14, daysOfWeek: [ { id: 1, name: "Saturaday" }, { id: 2, name: "Sunday" } ] } ]; const weekends = ["Saturaday","Sunday"] // Approach // we have to filter some element based on condition // condition will be days should not belong to weekends this.getPriceWeekDay = StrategypricingDetail.filter((rec) => { for(let dayIndex = 0; dayIndex < rec.daysOfWeek.length; dayIndex++){ const dayName = rec.daysOfWeek[dayIndex].name; if(weekends.includes(dayName)){ return; } } return rec; }).map(({price}) => price); console.log(getPriceWeekDay);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM