JavaScript按hotel_id和category分组并关联price的实现问题
Solution for Nested Hotel → Category → Price Grouping
Hey there! Let's sort out this nested grouping problem for you. You were already using reduce correctly as a starting point—you just needed to add an extra layer to map each category to its list of prices, instead of just collecting categories into an array.
Here's the revised code that achieves your desired hierarchy:
let myarray = [ { price: 257, category: 1, hotel_id: 4 }, { price: 493, category: 1, hotel_id: 3 }, { price: 514, category: 1, hotel_id: 3 }, { price: 257, category: 1, hotel_id: 3 }, { price: 104, category: 1, hotel_id: 3 }, { price: 295, category: 1, hotel_id: 3 }, { price: 125, category: 1, hotel_id: 2 }, { price: 125, category: 1, hotel_id: 2 }, { price: 157, category: 1, hotel_id: 2 }, { price: 125, category: 1, hotel_id: 2 }, { price: 125, category: 1, hotel_id: 1 }, { price: 43, category: 1, hotel_id: 1 }, { price: 43, category: 2, hotel_id: 1 }, { price: 43, category: 2, hotel_id: 1 } ]; // Step 1: Group data first by hotel_id, then by category (collecting prices) const groupedData = myarray.reduce((acc, item) => { // Create a hotel entry if it doesn't exist yet if (!acc[item.hotel_id]) { acc[item.hotel_id] = {}; } // Create a category entry for this hotel if it doesn't exist if (!acc[item.hotel_id][item.category]) { acc[item.hotel_id][item.category] = []; } // Add the current price to the category's price list acc[item.hotel_id][item.category].push(item.price); return acc; }, {}); // Step 2: Convert the grouped object into your desired array structure const hotels = Object.entries(groupedData).map(([hotelId, categoryMap]) => ({ hotel_id: hotelId, categories: Object.entries(categoryMap).map(([category, prices]) => ({ category: Number(category), // Convert string back to number if needed prices: prices })) })); console.log(hotels);
What this produces:
You'll get a nested structure where each hotel has a list of categories, and each category includes its associated prices—exactly what you were aiming for:
[ { "hotel_id": "1", "categories": [ { "category": 1, "prices": [125, 43] }, { "category": 2, "prices": [43, 43] } ] }, { "hotel_id": "2", "categories": [ { "category": 1, "prices": [125, 125, 157, 125] } ] }, { "hotel_id": "3", "categories": [ { "category": 1, "prices": [493, 514, 257, 104, 295] } ] }, { "hotel_id": "4", "categories": [ { "category": 1, "prices": [257] } ] } ]
Bonus: Add sorting if needed
If you want to sort the prices within each category, or sort categories by their number, you can tweak the code slightly:
- To sort prices in ascending order:
prices: prices.sort((a, b) => a - b) - To sort categories numerically:
categories: Object.entries(categoryMap) .sort(([catA], [catB]) => Number(catA) - Number(catB)) .map(([category, prices]) => ({ ... }))
内容的提问来源于stack exchange,提问作者Zaheer Ahmad
相关产品推荐
相关产品推荐

