I have 2 arrays
console.log(this.items) = userGroups
[
{
"id": 63,
"name": "URLGROUP-1643836551908"
}
]
console.log(urls)
userGroup can have URLs
[
[
{
"id": 110,
"group_id": 63,
"url": "https://www.apple.com",
"url_num": 1,
"max_iteration": 2
},
{
"id": 111,
"group_id": 63,
"url": "https://www.google.com",
"url_num": 2,
"max_iteration": 2
}
]
]
I'm trying to combine them like this : id, name, url
[
{
"id": 63,
"name": "URLGROUP-1643836551908",
"url": [
{
"id": 110,
"group_id": 63,
"url": "https://www.apple.com",
"url_num": 1,
"max_iteration": 2
},
{
"id": 111,
"group_id": 63,
"url": "https://www.google.com",
"url_num": 2,
"max_iteration": 2
}
]
}
]
I've tried merge, and I don't get a good result at all. I'm about to do for-loop within a forloop, but that will be bad for performance.
What should I do in case ?
If I do this
for (let i = 0; i < this.items.length; i ) {
for (let j = 0; j < urls.length; j ) {
if (i == j) {
this.items[i].urls = urls[j]
}
}
}
console.log(this.items)
I kind of get what I want:
[
{
"id": 63,
"name": "URLGROUP-1643836551908",
"details": [
{
"id": 110,
"group_id": 63,
"url": "https://www.acme.com",
"url_num": 1,
"max_iteration": 2
}
]
}
]
CodePudding user response:
Although the example is not varied enough to be sure, I will assume that the second array (of arrays) has grouped items with the same group_id
value in the same subarray.
You could create a Map
keyed by group_id
(the first found in a subarray), and assign to each the corresponding subarray.
Then map the first array to objects extended with a url
property that is taken from the Map
, based on the objects id
property:
let userGroups = [{"id": 63,"name": "URLGROUP-1643836551908"}];
let urls = [[{"id": 110,"group_id": 63,"url": "https://www.apple.com","url_num": 1,"max_iteration": 2},{"id": 111,"group_id": 63,"url": "https://www.google.com","url_num": 2,"max_iteration": 2}]];
let urlsMap = new Map(urls.map(arr => [arr[0].group_id, arr]));
let result = userGroups.map(obj => ({...obj, url: urlsMap.get(obj.id)}));
console.log(result);