Reputation: 2402
Hello let's take this example :
var legitTask = [
{
"guid": "beb033fd-f2ca-4bde-a732-4396d560b216",
"isActive": false,
"friends": [
{
"id": 33,
"name": "Rosalind Kaufman"
},
{
"id": 41,
"name": "Marion Armstrong"
},
{
"id": 52,
"name": "Sonia Baxter"
}
]
},
{
"guid": "2ac71ecb-4d7e-4c81-bd54-f6d17ce141a9",
"isActive": true,
"friends": [
{
"id": 023,
"name": "Viola Gillespie"
},
{
"id": 31,
"name": "Anita Bass"
},
{
"id": 12,
"name": "Galloway Townsend"
}
]
},
{
"guid": "07acf598-cb57-490f-a42c-3a0ee0a543fc",
"isActive": true,
"friends": [
{
"id": 0,
"name": "Lou Elliott"
},
{
"id": 71,
"name": "Christina Spence"
},
{
"id": 82,
"name": "Doris Garner"
}
]
}
]
Desired Final Result: Assign ONLY the isActive property of each parent to each of it friends
[ {
"id": 33,
"name": "Rosalind Kaufman",
"isActive": false
},
{
"id": 41,
"name": "Marion Armstrong",
"isActive": false
},
{
"id": 52,
"name": "Sonia Baxter",
"isActive": false
}, {
"id": 023,
"name": "Viola Gillespie"
"isActive": true
},
{
"id": 31,
"name": "Anita Bass"
"isActive": true
},
{
"id": 12,
"isActive": true
"name": "Galloway Townsend"
},
{
"id": 0,
"isActive": true,
"name": "Lou Elliott"
},
{
"id": 71,
"isActive": true,
"name": "Christina Spence"
},
{
"id": 82,
"isActive": true,
"name": "Doris Garner"
}
]
So my first step would be to pick the friends and the desired property :
let firstRound = _.map(legitTask, task =>{
return _.pick(task, ['isActive', 'friends']);
});
GREAT! I have now the desired property and each of the friends, now how to pass the property to each of the friends? (Assuming I have a BIG list so the 'best way' is a necessity, Yes I know I can loop and loop and loop, but that would really kill the performance )
🥴 Here where I'm stuck
_.forEach(firstRound, parent =>{
return _.map(parent.friends, task =>{
return _.assign(task, parent.isActive);
});
});
Upvotes: 0
Views: 33
Reputation: 454
When it comes to performance, I always find that vanilla JS is faster than any library implementation. So I always prefer vanilla JS for this reason. Here, a non-lodash.js solution, that places the desired values into the array, though you can simply deep-clone your original array:
const res = legitTask
.map(obj => {
return obj.friends.map(friend => {
friend.isActive = obj.isActive;
return friend;
});
})
.flat();
Alternatively, if you don't want to deepclone, you can use this implementation, which is slower, but keeps your old array intact:
const res = legitTask
.map(obj => {
return obj.friends.map(friend => {
const returnObj = { ...friend };
returnObj.isActive = obj.isActive;
return returnObj;
});
})
.flat();
Upvotes: 1
Reputation: 2205
You can try like this.
_.reduce(legitTask, (acc, {friends, ...rest}) => acc.concat(_.map(friends, friend => ({...friend,...rest }))), [])
Upvotes: 1