Search code examples
javascriptobjectmultidimensional-arraylodash

Group and merge in nested object using Lodash


I have an object data as follows:

[
    {
        name: "Green Tea Brownie",
        price: 60,
        amount: 10,
        seller: {
            seller_id: 124,
            seller_name: "Merry Shop"
        }      
    },
    {
        name: "Cocoa Chiffon",
        price: 20,
        amount: 50,
        seller: {
            seller_id: 124,
            seller_name: "Merry Shop"          
        }      
    },
    {
        name: "Milky Donut",
        price: 40,
        amount: 100
        seller: {
            seller_id: 421,
            seller_name: "Sweet Bakery"   
        }      
    }
]

So I want to group data by "seller_id" and merge top level data assigns to object name "orders", just look like as following:

[
    {
        seller_id: 124,
        seller_name: "Merry Shop",
        orders: [
            {
                name: "Green Tea Brownie",
                price: 60,
                amount: 10
            },
            {
                name: "Cocoa Chiffon",
                price: 20,
                amount: 50
            }
        ]
    },
    {
        seller_id: 421,
        seller_name: "Sweet Bakery",
        orders: [
            {
                name: "Milky Donut",
                price: 40,
                amount: 100
            }
        ]
    }
]

I tried to solve this problem several hours ago. Can anyone solve this case?

Thank you


Solution

  • You can use _.groupBy() and then _.map() the groups to requested format:

    const { flow, partialRight: pr, groupBy, map, first, omit } = _
    
    const fn = flow(
      pr(groupBy, 'seller.seller_id'),
      pr(map, group => ({
        ...first(group).seller,
        orders: map(group, pr(omit, 'seller'))
      }))
    )
    
    const data = [{"name":"Green Tea Brownie","price":60,"amount":10,"seller":{"seller_id":124,"seller_name":"Merry Shop"}},{"name":"Cocoa Chiffon","price":20,"amount":50,"seller":{"seller_id":124,"seller_name":"Merry Shop"}},{"name":"Milky Donut","price":40,"amount":100,"seller":{"seller_id":421,"seller_name":"Sweet Bakery"}}]
    
    const result = fn(data)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>