# obj.mergeWith()

[JS](../../../..) ⟩ [object](../../../obj) ⟩ [built-in](../..) ⟩ [Object](..) ⟩ [extension]() ⟩ obj.mergeWith(...sources)

{% tabs %}
{% tab title="💾 程式" %}
* replit ⟩ [obj.mergeWith(...sources)](https://replit.com/@pegasusroe/objmergeWithsources#ext/Object_ext.js), compare with [.assigndescriptors](../../../obj/extend/mixin/.assigndescriptors "mention")
* require [](<> "mention")

```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 [](<> "mention")

```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](../../../obj/extend/object.assign "mention")
* [extend](../../../obj/extend "mention")
* this method needs to [enumerate](../../../obj/prop/enumerate "mention") and deal with their [attr](../../../obj/prop/attr "mention")(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 %}
