Append array to atribute of another array (javascript)

Viewed 48

I'm learning Javascript and I'm stuck in a doubt with the joining of two arrays of objects through an ID, I can join the two, but the result is not what I expect.

So, I have these two object arrays:

"product": [
        {
            "id": "1000",
            "code": "f230fh0g3",
            "name": "Bamboo Watch",
            "description": "Product Description",
            "image": "bamboo-watch.jpg",
            "price": 65,
            "category": "Accessories",
            "quantity": 24,
         }
]

"orders": [            
       {                
            "id": "1000",             
            "productID": "f230fh0g3",           
            "date": "2020-09-13",
            "amount": 65,
            "quantity": 1,
       },
       {                
            "id": "1000",             
            "productID": "f230fh0g3",           
            "date": "2020-09-13",
            "amount": 65,
            "quantity": 1,
       },
]

and I want to join both by key (id) to get one array like this one:

"product": [
        {
            "id": "1000",
            "code": "f230fh0g3",
            "name": "Bamboo Watch",
            "description": "Product Description",
            "image": "bamboo-watch.jpg",
            "price": 65,
            "category": "Accessories",
            "quantity": 24,
            "orders": [
                {
                    "id": "1000",
                    "productCode": "f230fh0g3",
                    "date": "2020-09-13",
                    "amount": 65,
                    "quantity": 1,
                    "customer": "David James",
                    "status": "PENDING"
                },
                {
                    "id": "1001",
                    "productCode": "f230fh0g3",
                    "date": "2020-05-14",
                    "amount": 130,
                    "quantity": 2,
                    "customer": "Leon Rodrigues",
                    "status": "DELIVERED"
                },
              ]
    },
    {
         "id": "1001",
         "..."
         "orders": [
               {
                     "id": "1001",
                     "..."
               }
           ]
    }]

Is it possible to map these arrays in this way? Thanks in advance

1 Answers

Yes, it is possible. You can use .map() and .filter() together. Assuming you have products in product variable and orders in order variable, you can compute your combined list like this:

const result = products.map(
    product => ({
        ...product,
        orders: orders.filter(
            ({ productID }) => productID === product.id
        )
    })
);
Related