JavaScript - Extend Properties of Source Object to Destination Object

Viewed 18

I've got this problem for precourse for a bootcamp:

// Assigns own enumerable properties of source object(s) to the destination
// object. Subsequent sources overwrite property assignments of previous sources.
// extend({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
// should return ->  { 'user': 'fred', 'age': 40 }
// BONUS: solve with reduce

I've seen other questions on here solve this successfully using reduce (which I am still learning). However - I am trying to figure out why exactly the methods I used are being marked as incorrect by the testing site I'm given.

Here is a correct answer given on another question on here:

function extend(...destination) {
  return destination.reduce(function(acc, val){
    var keys = Object.keys(val),
    key = null;
    for(var keyIdx = 0, len = keys.length; keyIdx < len; keyIdx++){
      key = keys[keyIdx];
      acc[key] = val[key];
    }
    return acc;
  });

Here are two of my answers that both got the same output - but were marked wrong. I assume this is because of object reference, but I am having trouble finding the exact problem.

function extend(...destination) {
  const newObj = {};
  destination.forEach(x => {
    var keys = Object.keys(x);
    for (let i = 0; i < keys.length; i++){
      const key = keys[i];
      newObj[key] = x[key];
    }
  });

  return newObj;

and

function extend(...destination) {
  const newObj = {};
  destination.forEach(x => {
    Object.assign(newObj, x);
  });
  return newObj;

Thanks in advance! Sorry if this is a dumb question - my first ask on here.

1 Answers

The first argument to the function is the destination object that should be modified in place. You're creating a new object instead of modifying the first object in place.

Split the arguments into a single destination and spread sources. Then your loop can be used to update destination.

function extend(destination, ...sources) {
  sources.forEach(x => {
    var keys = Object.keys(x);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      destination[key] = x[key];
    }
  });

  return destination;
}

const obj = { 'user': 'barney' };

extend(obj, { 'age': 40 }, { 'user': 'fred' });
console.log(obj);

Related