Reputation: 1449
I have constructed objects as follow:
Object 1
[ {
ext: '1287',
ip: '(Unspecified)',
queue: [ ]
} ]
Object 2
[ { Queue: '222',
Members:
[ {"ext":"1287"},
{"ext":"4118"} ],
Callers: [] },
{ Queue: '111',
Members:
[ {"ext":"4131"},
{"ext":"1287"},
{"ext":"4138"}
],
Callers: [] }]
I want to compare Object 1 and Object 2. If the value of ext key from Object 1 exists in the nested Members object of Object 2 then the value of Queue should be pushed to a queue array and the final object should be like as shown below.
Final Object that I want
[{ ext: '1287',
ip: '(Unspecified)',
queue: [222, 111 ] }]
I need some hints regarding how a nested object like this is compared using lodash.
Upvotes: 0
Views: 2781
Reputation: 28445
You can try following using Array.forEach and Array.some
let obj1 = [{ext: '1287',ip: '(Unspecified)',queue: []}];
let obj2 = [{Queue: '222',Members: [{"ext":"1287"},{"ext":"4118"}],Callers: []},{Queue: '111',Members: [{"ext":"4131"},{"ext":"1287"},{"ext":"4138"}],Callers: []}];
obj1.forEach(o => {
obj2.forEach(v => {
let exists = v.Members.some(m => m.ext === o.ext);
if (exists) o.queue.push(v.Queue);
});
});
console.log(obj1);
Improvement
You can improve the performance by first creating a map
of obj1
with ext
as key
and object
as value
. Use Array.reduce and Object.assign
let obj1 = [{ext: '1287',ip: '(Unspecified)',queue: []}];
let obj2 = [{Queue: '222',Members: [{"ext":"1287"},{"ext":"4118"}],Callers: []},{Queue: '111',Members: [{"ext":"4131"},{"ext":"1287"},{"ext":"4138"}],Callers: []}];
let map = obj1.reduce((a, c) => Object.assign(a, {[c.ext] : c}), new Map());
obj2.forEach(v => {
v.Members.forEach(m => {
if(map[m.ext]) map[m.ext].queue.push(v.Queue);
});
});
console.log(obj1);
Upvotes: 3
Reputation: 11600
Solution without mutations:
const obj1 = [{ext: '1287',ip: '(Unspecified)',queue: []}];
const obj2 = [{Queue: '222',Members: [{"ext":"1287"},{"ext":"4118"}],Callers: []},{Queue: '111',Members: [{"ext":"4131"},{"ext":"1287"},{"ext":"4138"}],Callers: []}];
const hasExt = ext => o2 => o2.Members.some(m => m.ext === ext)
const result = obj1.map(o1 => {
const newQueue = obj2
.filter(hasExt(o1.ext))
.map(m => m.Queue);
return { ...o1, queue: [...o1.queue, ...newQueue] };
})
console.log(result);
Upvotes: 1