Reputation: 8851
I'm trying to do a matching between an object of objects (A) and an array of objects (B).
Each object in the object of objects has a PID. Each object in the array of objects has a PID. I am trying to match A and B so I can get the occupation from A, and then append the occupation to each object in B. So, I am trying to get PID and Occupation into one. Can this even be done?
So, here's what A might look like:
{
emp1: {
PID: 2430
Occupation: Welder
},
emp2: {
PID: 432,
Occupation: Electrician
}
}
and B:
[
{
PID: 432
},
{
PID: 2430
}
]
Can this be easily done using something like lodash library?
Upvotes: 0
Views: 31
Reputation: 6742
You would need to run a loop inside loop to match elements from B to A (or other way round) which is quite expensive. It would have been much easier if you could change structure of, let's say, A.
A = {
2430: {
name: "John",
occupation: "Welder"
},
432: {
name: "John",
occupation: "Electrician"
}
}
Then you can access data in A
like this: A[2430]
Then your code could look like that:
B = B.map(function(el) {
return {
PID: el.PID,
occupation: A[el.PID].occupation
}
});
console.log(B);
So you have just one loop. Also you benefit from much faster access to data from A
in the future.
Upvotes: 1