javascriptobject

adding a property to an object in javascript


function addProperty(object, property) {
  // add the property to the object with a value of null
  // return the object
  // note: the property name is NOT 'property'.  The name is the value of the argument called property (a string)
}

I got a little stuck on an only home work question. I think I understand what its asking me to do. I want to pass in an object and add a new property and set its default value to null.

Here is what I have tried doing

function addProperty(object, property) {
  // add the property to the object with a value of null
  // return the object
  // note: the property name is NOT 'property'.  The name is the value 
  object.property = property;
  object[property] = null;
  return object;
    }

This does not seem to be working the way I need it to as I believe I the object should produce something like

const object = {
propertyPassedIn: null,
};

can anyone help or point me in the right direction?


Solution

  • This works for me

    function addProperty(object, property) {
      // add the property to the object with a value of null
      // return the object
      // note: the property name is NOT 'property'.  The name is the value 
      // object.property = property;
      object[property] = null;
      return object;
    }
    
    var obj = {x:1,y:null};
    // undefined
    obj
    // {x: 1, y: null}
    addProperty(obj, 'z');
    // {x: 1, y: null, z: null}