> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/object/ext/merge-with.md).

# obj.mergeWith()

[JS](/web/js.md) ⟩ [object](/web/js/val/obj.md) ⟩ [built-in](/web/js/val/builtin.md) ⟩ [Object](/web/js/val/builtin/object.md) ⟩ [extension](/web/js/val/builtin/object/ext.md) ⟩ obj.mergeWith(...sources)

{% tabs %}
{% tab title="💾 程式" %}

* replit ⟩ [obj.mergeWith(...sources)](https://replit.com/@pegasusroe/objmergeWithsources#ext/Object_ext.js), compare with [.assignDescriptors()](/web/js/val/obj/extend/mixin/.assigndescriptors.md)
* require [Object extension](/web/js/val/builtin/object/ext.md)

```javascript
Object.defineProperties(Object.prototype, {

    // 🔹 other related methods omitted ...
    
    // 🔹 obj.mergeWith(...sources)
    mergeWith: {
        value: function(...sources) {

            const descriptors = {};
            
            // collect all descriptors from sources
            sources.forEach(source => {
                
                // own enumerable (string-keyed) properties -> descriptors
                source.keys.forEach(key => {
                    descriptors[key] = source.propertyDescriptor(key);
                });
        
                // own enumerable (symbol-keyed) properties -> descriptors
                source.symbols.forEach(sym => {
                    const desc = source.propertyDescriptor(sym);
                    if (desc.enumerable) descriptors[sym] = desc;
                });
        
            });
        
            // merge
            return this.defineProperties(descriptors);
        },
    },

});
```

{% endtab %}

{% tab title="💈範例" %}

* [replit](https://replit.com/@pegasusroe/objmergeWithsources#index.js), require [Object extension](/web/js/val/builtin/object/ext.md)

```javascript
const source = {
  x: 1,                  // data property
  get y() { return 2 },  // accessor (getter)
};

({}).assign(source)      // { x: 1, y: 2 }
({}).mergeWith(source)   // { x: 1, y: [Getter] }
```

{% endtab %}

{% tab title="👥 相關" %}

* compare with [Object.assign()](/web/js/val/obj/extend/object.assign.md)
* [extending objects](/web/js/val/obj/extend.md)
* this method needs to [property enumeration](/web/js/val/obj/prop/enumerate.md) and deal with their [attribute](/web/js/val/obj/prop/attr.md)(s).
  {% endtab %}

{% tab title="📘 手冊" %}

* [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) ⟩ [copying accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#copying_accessors)
  {% endtab %}
  {% endtabs %}
