I am working on a problem where I have to group an array of objects from one form into another.
An example is better than 1000 words:
var initialData = [
{
house: { id: 1, text: "white" },
room: { id: 1, text: "red" },
price: 2.1
},
{
house: { id: 1, text: "white" },
room: { id: 2, text: "blue" },
price: 3.1
},
{
house: { id: 1, text: "white" },
room: { id: 3, text: "red" },
price: 5.8
},
{
house: { id: 2, text: "black" },
room: { id: 1, text: "yellow" },
price: 9.1
},
{
house: { id: 2, text: "black" },
room: { id: 2, text: "green" },
price: 7.7
},
];
And the new object should look like this:
var finalObject = {
houses: [
{
id: 1, text: "white",
rooms: [
{ id: 1, text: "red", price: "2.1" },
{ id: 2, text: "blue", price: "3.1" },
{ id: 3, text: "red", price: "5.8" }
]
},
{
id: 2, text: "black",
rooms: [
{ id: 1, text: "yellow", price: "9.1" },
{ id: 2, text: "green", price: "7.7" }
]
}
]
};
I have to find unique houses with all their rooms and also to add each price from initial object inside room.
I'm wondering which would be the best way to do this since I will have a huge amount of elements?
I have some ideas with multiple loops, but to me it seems a bit too complex my solution.
Update: my question is not the same as the one candidate for duplication because I don't use lodash, and my object has to be refactored a bit, not just regrouped.
Possible solution (inspired by @Gael's answer)
finalObject = {}
for (var i = 0; i < initialData.length; ++i) {
var item = initialData[i];
var id = item.house.id;
if(!finalObject[id]) {
finalObject[id] = item.house;
finalObject[id].rooms = [];
}
var room = item.room;
room.price = item.price;
finalObject[id].rooms.push(room);
}
console.log(finalObject);