merge

Modified on Thu, 9 Jul at 10:50 AM

merge

TABLE OF CONTENTS

Merge objects

Definition

object merge(object *argument, [, object $...])

Accepts one or more objects as arguments and returns a single object with subsequent objects merged. Each subsequent object’s key/value pairs are added to the preceding object. If there are keys that appear in multiple objects, the value of the key from the last such object is the one that will appear in the result. This holds except if the values are objects or arrays. Objects are not overwritten, but merged again with the same logic, and array values are concatenated together instead of being overwritten.

Parameters

object *argument

One or more objects to merge.

Returns

object

Object obtained by merging the later objects into the first one. Non-array and non-object values of the resulting object will be the values of the key in the last object argument that had it as a property. Arrays are concatenated together, while the merge logic is applied again on object values.

Example

Sample data
{
  "John1": {
    "middleName": "Jim",
    "lastName": "Smith",
    "age": 42,
    "address": {
      "street": "Main Street",
      "houseNumber": 1,
      "cohabitants": ["Jane", "Julia"]
    },
    "siblings": ["Jade", "Jack"]
  },
  "John2": {
    "middleName": null,
    "lastName": "Doe",
    "address": {
      "street": "High Street",
      "apartmentNumber": 2,
      "cohabitants": ["Jane", "James"]
    },
    "siblings": ["Jerry"]
  }
}
Transformation
{
  john: merge(John1, John2)
}
Result
{
  "john": {
    "middleName": "Jim",
    "lastName": "Doe",
    "age": 42,
    "address": {
      "street": "High Street",
      "houseNumber": 1,
      "cohabitants": ["Jane", "Julia", "Jane", "James"],
      "apartmentNumber": 2
    },
    "siblings": ["Jade", "Jack", "Jerry"]
  }
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article