【问题标题】:Patch objects with RXJS使用 RXJS 修补对象
【发布时间】:2016-10-10 05:10:11
【问题描述】:

我相信我想要实现的类似于 HTTP 补丁或深度扩展功能,但我想用 rxjs 来实现。假设我有以下对象:

const arr1 = {
  obj1: { a: 'dog', b: 'cat', c: 'bird' },
  obj2: { a: 'boy', b: 'girl', c: 'guitar' },
  obj3: { a: '1', b: '2', c: '3' }
}

const arr2 = {
  obj1: { a: 'wolf', b: 'lion', c: 'hawk', z: 'bear' },
  obj2: { c: 'car'}
}

然后我想使用 rxjs 来获得以下输出:

const output = {
  obj1: { a: 'wolf', b: 'lion', c: 'hawk', z: 'bear' },
  obj2: { a: 'boy', b: 'girl', c: 'car' },
  obj3: { a: '1', b: '2', c: '3' }
}

有没有一种有效的方法来实现这一点?

【问题讨论】:

  • 您能进一步解释一下您的情况吗?在这里使用 RxJS 的原因是什么?如果所有数据片段都是对象并且在当前时刻都在一个片段中可用,那么我看不出它与 RxJS 有什么关系。它只是深度合并/扩展,有很多不同的风格(顺便说一句,它们是对象的对象,而不是数组)。

标签: angular rxjs ngrx


【解决方案1】:

RxJS 不是用来合并对象的,它是An API for asynchronous programming with observable streams

如果要合并对象可以使用Lodash merge

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

或对象扩展运算符(未官方支持) https://babeljs.io/docs/plugins/transform-object-rest-spread/

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2018-12-27
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多