Skip to content

Merge JavaScript objects in array with same key es6 | Example code

  • by

Using the lodash method .merge(), you can Merge JavaScript objects in an array with the same key es6.

const result = _.merge(arr1, arr2)

Read more options: JavaScript merges an array of objects by key

Merge JavaScript objects in array with same key es6

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
</head>
<body>

  <script>
   const listOfQuestions = [{
    question1: {
      important: true
    }
  }, {
    question2: {
      important: false
    }
  }];

  const listOfAnswers = [{
    question1: {
      answer: false
    }
  }, {
    question2: {
      answer: true
    }
  }];

  const result = _.merge(listOfQuestions, listOfAnswers)
  console.log(result)
</script>

</body>
</html>

Output:

Another way

var arr = [
{
    "abc": [
        {
            "name": "test",
            "addr": "123",
       }
    ]
},
{
    "def": [
        {
            "first_name": "test",
            "last_name": "test"
        }
    ]
},
{
    "def": [
        {
            "first_name": "test1",
            "last_name": "test1"
        }
    ]
}]

const result = arr.reduce((acc, curr) => {        
    const key = Object.keys(curr)[0]
    const found = acc.find(i => i[key])
    if (!found) {
        acc.push(curr)
    } else {
        found[key] = [ ...found[key], ...curr[key] ]
    }
    return acc;
}, [])

console.log(result)

Output:


[
  {
    "abc": [
      {
        "name": "test",
        "addr": "123"
      }
    ]
  },
  {
    "def": [
      {
        "first_name": "test",
        "last_name": "test"
      },
      {
        "first_name": "test1",
        "last_name": "test1"
      }
    ]
  }
]

Merge two arrays of objects based on a key

let arr1 = [
    { id: "abdc4051", date: "2017-01-24" },
    { id: "abdc4052", date: "2017-01-22" }
];

let arr2 = [
    { id: "abdc4051", name: "ab" },
    { id: "abdc4052", name: "abc" }
];

let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

console.log(arr3);

Output:


[
  {
    "id": "abdc4051",
    "date": "2017-01-24",
    "name": "ab"
  },
  {
    "id": "abdc4052",
    "date": "2017-01-22",
    "name": "abc"
  }
]

Do comment if you have any doubts or suggestions on this Js merge topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *