How to merge two arrays which are inside individual objects as property
Object.assign(obj1, obj2).slotIDs
const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }
const result = Object.assign(obj1, obj2).slotIDs
console.log(result)
With Vanilla JS you can iterate with Array.flatMap()
and return the slotIDs
to get an array of ids. To remove duplicates, create a Set from the array, and spread the Set back to an array:
const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }
const result = [...new Set([obj1, obj2].flatMap(o => o.slotIDs))]
console.log(result)
With lodash you can iterate with _.flatMap()
and take the slotIDs
to get an array of ids. Use _.uniq()
To remove duplicates:
const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }
const result = _.uniq(_.flatMap([obj1, obj2], 'slotIDs'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
One line of code solution:
let obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
let obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }
const result = [...new Set([...obj1.slotIDs, ...obj2.slotIDs])]
console.log(result)
Try
let newObj= []
for(const value in Object.assign(obj1,obj2)["slotIDs"])
newObj.push(Object.assign(obj1,obj2)["slotIDs"][value])
Edit- Here's a simpler or one-line version.
let newObj=Object.assign(obj1,obj2)["slotIDs"]
As @OriDrori Suggested, the above methods alters the obj1 itself and doesn't works well in similar questions where Obj1 has multiple key, value pair. Here's what you do to avoid that
let newObj=Array.from(new Set(obj1.slotIDs.concat(obj2.slotIDs)))
Quick Note- Use of Array.from()
is optional.