[英]How to merge two arrays which are inside individual objects as property
我有两个这样的对象:
let obj1 = { slotIDs: ["5e0301f353ee2a0546298f15"] }
let obj2 = { slotIDs: ["5e0301f353ee2a0546298f15", "5e03050453ee2a0546298f1c"] }
我需要像这样将它们合并到一个数组中
let newObj = ["5e0301f353ee2a0546298f15", "5e03050453ee2a0546298f1c"]
我试过使用 lodash union 和 map 但没有运气。
一行代码解决:
let obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] } let obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] } const result = [...new Set([...obj1.slotIDs, ...obj2.slotIDs])] console.log(result)
使用 Vanilla JS,您可以使用Array.flatMap()
进行迭代并返回slotIDs
以获取 id 数组。 要删除重复项,请从数组中创建一个 Set,然后将 Set 传播回数组:
const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] } const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] } const result = [...new Set([obj1, obj2].flatMap(o => o.slotIDs))] console.log(result)
使用 lodash,您可以使用_.flatMap()
进行迭代并获取slotIDs
以获取 id 数组。 使用_.uniq()
删除重复项:
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>
尝试
let newObj= [] for(const value in Object.assign(obj1,obj2)["slotIDs"]) newObj.push(Object.assign(obj1,obj2)["slotIDs"][value])
编辑 - 这是一个更简单或单行的版本。
let newObj=Array.from(new Set(obj1.slotIDs.concat(obj2.slotIDs)))
正如@OriDrori 所建议的那样,上述方法会改变 obj1 本身,并且在 Obj1 具有多个键值对的类似问题中效果不佳。 这是你为避免这种情况所做的
let newObj=Array.from(new Set(obj1.slotIDs.concat(obj2.slotIDs)))
快速说明 - Array.from()
是可选的。
Object.assign(obj1, obj2).slotIDs
const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] } const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] } const result = Object.assign(obj1, obj2).slotIDs console.log(result)
编辑:
let obj1 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e0301f353ee2a0546298f16'] } let obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] } let result = Array.from( new Set(obj1.slotIDs.concat(obj2.slotIDs)) ) console.log(result)
旧答案:
{ ...obj1, ...obj2 }.slotIDs
怎么{ ...obj1, ...obj2 }.slotIDs
?
let obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] } let obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] } let result = { ...obj1, ...obj2 }.slotIDs console.log(result)
如果您的对象可以具有保存数组值的其他属性,并且您希望将所有这些属性合并到一个唯一的数组中,您可以使用Object.entries()
和.map()
然后使用Set
来删除重复项:
const obj1 = { slotIDs: ["5e0301f353ee2a0546298f15"], itemIds: ["xyz123"] }; const obj2 = { slotIDs: ["5e0301f353ee2a0546298f15", "5e03050453ee2a0546298f1c"], itemids: ["xyz123", "abc123"] }; const res = [...new Set([obj1, obj2].map(Object.values).flat(2))]; console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.