gpt4 book ai didi

javascript - 合并两个对象并增加 ECMAScript 6 中的键

转载 作者:行者123 更新时间:2023-11-30 07:07:17 25 4
gpt4 key购买 nike

我想将几个对象合并在一起,但是因为它们的键是相等的,所以在使用 Object.assign() 时它只返回与最后一个对象相同的属性。

let obj1 = {0: "a", 1: "b", 2: "c", 3: "d"};
let obj2 = {0: "e", 1: "f", 2: "g", 3: "h"};

但是我想要的输出

let output = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h"};

最佳答案

你真的应该为此使用数组。这会让你的生活更轻松。

话虽如此,您可以从将成为数组的对象中获取,连接它们,然后创建一个新对象:

let obj1 = {0: "a", 1: "b", 2: "c", 3: "d"}
let obj2 = {0: "e", 1: "f", 2: "g", 3: "h"}

let obj = Object.values(obj1).concat(Object.values(obj2))
.reduce((a, c, i) => (a[i] = c, a), {})
console.log(obj)

您还可以使用扩展语法:

let obj1 = {0: "a", 1: "b", 2: "c", 3: "d"}
let obj2 = {0: "e", 1: "f", 2: "g", 3: "h"}

let obj = {...Object.values(obj1).concat(Object.values(obj2))}
console.log(obj)

像这样的情况应该发生什么是模棱两可的:

let obj1 = {0: "a", 1: "b", 2: "c", 4: "d"}
let obj2 = {0: "e", 1: "f", 2: "g", 3: "h"}

关于javascript - 合并两个对象并增加 ECMAScript 6 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com