Home > Enterprise >  concatenate 2 object that get from axios request in vue
concatenate 2 object that get from axios request in vue

Time:08-10

there are users data that get by location ids. the locations data look like this

locations = ([
         { "name" : "St Skid row" , "id" : 1},
         { "name" : "St Manhatan" , "id" : 2},
         { "name" : "St Golf" , "id" : 3}
      ])

lets say the users data in databases look like this

users = [
{"name" : "rikardo", "locationId" : 1},
{"name" : "valention", "locationId" : 1},
{"name" : "marcello", "locationId" : 2},
{"name" : "Ronaldo", "locationId" : 2},
{"name" : "Adriano", "locationId" : 3},
]

then get user by locations id

userBylocationIds.value = await axios.post(`${API_ORIGIN}/auth/v1/user/location`,locationIds

return data look like this

dataUsersByLocationId = [
   {"name" : "rikardo" },
   {"name" : "valention" },
   {"name" : "marcello" },
   {"name" : "Ronaldo" },
   {"name" : "Adriano" },
]

i want to combine both object, but i cant because dataUsersByLocationId did'n contain location id

expected after join

expected = [
   {"name" : "rikardo" ,"location": "St Skid row"}
   {"name" : "valention" ,"location": "St Skid row"}
   {"name" : "marcello" ,"location": "St Manhatan"} 
   and so on
]

CodePudding user response:

You have locationIds before, why you dont use locationIds to get your expected data?

CodePudding user response:

You can use Array.reduce on users array and get a combine array of user and location

const combineArray = users.reduce((pre, cur) => {
    const userLocation = locations.filter(loc => loc.id === cur.locationId)[0];
    pre.push({name: cur.name, location: userLocation.name});
    return pre;
}, []);

return value:

[
        {
            "name": "rikardo",
            "location": "St Skid row"
        },
        {
            "name": "valention",
            "location": "St Skid row"
        },
        {
            "name": "marcello",
            "location": "St Manhatan"
        },
        {
            "name": "Ronaldo",
            "location": "St Manhatan"
        },
        {
            "name": "Adriano",
            "location": "St Golf"
        }
    ]
  • Related