Search code examples
javascriptarraysobjectextendreduce

use reduce to extend enumerable properties of source object(s) to the destination object


I'm working on a JavaScript function that will assign the enumerable properties of a source object (or objects-- that's important) to the destination object. An additional stipulation is that subsequent sources overwrite the property assignments of previous sources.

I have indeed searched and read many similar questions, but I run into trouble for a couple reasons. To be honest, I've been stuck on it for three days.

Trouble spot 1: The boilerplate provided is just function extend(){} with no parameters. I'm not sure whether or not to add arguments. I'm sure it could be written either way.

Trouble spot 2: I can write code that successfully extends one object to another, but nothing that extends from multiple sources.

So for example, if the function were to be called thusly:

extend({ 'name': 'lola' }, { 'age': 9 }, { 'name': 'mickey' });

The result should be { 'user': 'mickey', 'age': 9 }

Guidance is greatly appreciated.


Solution

  • this seems like a perfect situation for Object.assign, It's an ES6 feature so check support on your target browsers;

    var objects = [{ 'name': 'lola' }, { 'age': 9 }, { 'name': 'mickey' }]
    
    var r = objects.reduce((a,b) => Object.assign(a,b));
    
    console.log(r)

    in this snippet I use [].reduce for looping through the array of objects and executing against the accumulator object; this will modify the first entry of the array..


    using the spread operator and assigning to a new object is probably a better solution:

    var objects = [{ 'name': 'lola' }, { 'age': 9 }, { 'name': 'mickey' }]
    
    var r = Object.assign({}, ...objects )
    
    console.log(r)