【问题标题】:Combine objects values into the single object将对象值组合到单个对象中
【发布时间】:2020-08-08 00:01:21
【问题描述】:

我有两个对象 -

a = {0:"hai",1:"hello"}
b = {0:"what",1:"you"}

我想得到以下格式的合并对象

c = {0:"hai",1:"hello",2:"what",3:"you"}

我尝试了不同的合并技术,但未能实现。实现上述目标的最佳方法是什么?

【问题讨论】:

  • 我希望之前的值也存在。提到的答案都没有帮助。

标签: javascript html reactjs typescript


【解决方案1】:

任意数量输入对象的通用方法


考虑到您想按出现顺序合并对象(使用重叠键),我可能会建议以下(适用于任意数量的输入对象)

以下是作为概念证明的现场演示:

const a = {0:"hai",1:"hello"},
      b = {0:"what",1:"you"},
      
      mergeObjects = (...args) => ({...args.flatMap(Object.values)}),
      
      c = mergeObjects(a,b)
      
console.log(c)
.as-console-wrapper{min-height:100%;}

但是,由于您似乎没有使用对象键,并且可能需要纯数组,因此您可以这么简单:

const a = {0:"hai",1:"hello"},
      b = {0:"what",1:"you"},
      
      mergeObjects = (...args) => args.flatMap(Object.values),
      
      c = mergeObjects(a,b)
      
console.log(c)
.as-console-wrapper{min-height:100%;}

【讨论】:

    【解决方案2】:

    这是一个解决方案,基本上将对象转换为数组,然后使用 Array.prototype.concat 将它们合并在一起:

    Object.assign([], {0:"hai",1:"hello"}).concat(Object.assign([], {0:"what",1:"you"}))
    

    【讨论】:

    • 以上返回数组,而 OP 请求了一个对象
    • 数组只是具有更多辅助方法的对象。如果你真的讨厌辅助方法,那么你可以输入一个Object.assign({}, stuff),其中stuff 是我在上面发布的代码。
    • '...you can just'能做的whole lot better,但是我们在这里谈论的是您的解决方案,基本上是答案的一半
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 2022-10-17
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多