Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have three array of objects like arr_1,arr_2 and arr_3 and i tried to merge all this three objects together but i am not getting what i try to want
JavaScript
const arr_1 = [
                {"user_id": "3","user_name": "Jack"},
                { "user_id": "4", "user_name": "Doe"}
              ];
const arr_2 = [
                {"user_id": "3","address": "New York" },
                {"user_id": "3","address": "California"},
                {"user_id": "4", "address": "Miami"},
                { "user_id": "4","address": "Turkey"}
              ];

const arr_3 = [
               { "user_id": "3","category_id": "3"},
               {"user_id": "3", "category_id": "4" },
               { "user_id": "4","category_id": "6" },
               { "user_id": "4","category_id": "7"}
             ];

////after merging this i want result like that 
const result = [
                  { "user_id": 3,"user_name": "Jack",
                    "address": ["New York","California"],
                    "category_id": ["3","4"]
                  },
                 { "user_id": 4, "user_name": "doe",
                   "address": ["Miami", "Turkey"],
                   "category_id": ["6","7"]
                 },
              ]
///// but m getting this 

result= [
                 { "user_id": 3,"user_name": "Jack",
                    "address": "New York",
                    "category_id": "3"
                  },
                { "user_id": 4,"user_name": "doe",
                    "address": "Miami",
                    "category_id": "6"
                  },

        ]


What I have tried:

const result = arr_1.map(t1 =>
               ({...t1, ...arr_2.find(t2 => t2.user_id === t1.user_id),
                 ...arr_3.find(t3=> t3.user_id=== t1.user_id)
                 }))
Posted
Updated 21-Jan-21 3:16am

1 solution

The find[^] method returns the first matching object. To return all matching objects, use the filter[^] method instead.

You will also need to map the objects from your second and third arrays to extract the property you want, and specify a property name for the resulting arrays.

For example:
JavaScript
const result = arr_1.map(t1 => ({
    ...t1, 
    address: arr_2.filter(t2 => t2.user_id === t1.user_id).map(t2 => t2.address),
    category: arr_3.filter(t3=> t3.user_id=== t1.user_id).map(t3 => t3.category_id)
}));
Demo[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900