Merging array of Objects in Javascript | Es6

We can use reduce function to merge array of objects in JavaScript, but you have to look out for a gotcha that is to provide an initialValue = {}; Here is the following code
function unproperMergeArrayofObjects(array){
    try{
       return array.reduce((a,b)=>Object.assign(a,b));
    }
    catch (err) {
        console.error(err);
        return null;
    }

}
function propermergeArrayofObject(array) {
    var initialValue={};
    return array.reduce((a,b)=>Object.assign(a,b),initialValue);
}

console.log('unproper',unproperMergeArrayofObjects([]));
var a={a:1};
console.log('unproper',unproperMergeArrayofObjects([a,{b:2}]));
console.log('proper',propermergeArrayofObject([]));
console.log('proper',propermergeArrayofObject([{a:1},{b:2}]));

Share this post

Leave a comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.