如何将两个位于单个对象内的数组合并为 属性

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)

尝试

let newObj= []
for(const value in Object.assign(obj1,obj2)["slotIDs"])
newObj.push(Object.assign(obj1,obj2)["slotIDs"][value])

编辑 - 这是一个更简单的或单行版本。

let newObj=Object.assign(obj1,obj2)["slotIDs"]

正如@OriDrori 建议的那样,上述方法改变了 obj1 本身,并且在 Obj1 具有多个键值对的类似问题中效果不佳。以下是您可以采取的措施来避免这种情况

let newObj=Array.from(new Set(obj1.slotIDs.concat(obj2.slotIDs)))

快速说明 - Array.from() 的使用是可选的。

编辑:

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怎么样?

let obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
let obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }

let result = { ...obj1, ...obj2 }.slotIDs

console.log(result)

使用 Vanilla JS,您可以使用 Array.flatMap() 和 return 和 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>

Object.assign(obj1, obj2).slotIDs

const obj1 = { slotIDs: ['5e0301f353ee2a0546298f15'] }
const obj2 = { slotIDs: ['5e0301f353ee2a0546298f15', '5e03050453ee2a0546298f1c'] }

const result = Object.assign(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);