I am working on a problem when I need to group an array of objects from one form to 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 need to find unique houses with all their rooms, and also add every price from the original object inside the room.
I am wondering what would be the best way to do this, since I will have a huge amount of elements?
I have some ideas with several cycles, but for me it seems too complicated for my solution.
Update: my question does not coincide with the only candidate for duplication, because I do not use lodash, and my object should be reorganized a bit, and 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);