2
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?

1
  • 1
    function addProperty(object, property) { object[property] = null; return object; } which you said you tried (at least part of your function did). What's the problem? Commented Mar 18, 2018 at 0:31

4 Answers 4

3

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}
Sign up to request clarification or add additional context in comments.

Comments

2

The preferred way of doing this if you ask me is to use Object.assign. This will copy all the properties of the second object you pass in into the first object. You can also send in multiple objects and all will be copied into the first object.

function addProperty(object, property) {
    return Object.assign(object, { [property]: null });
}

Comments

1

Just remove

object.property = property;

from your sample. This line would create a ReferenceError if the property is not already in the object. Other than that, I can't see a reason why it wouldn't do what you say you expect.

Comments

0
function addProperty(object, property) {
  object[property] = null;
  return object;
}

    var obj = {
       key1:1,
       key2:2
    };

addProperty(obj, 'value');
this will give below result
{key1:1, key2:2, value:null}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.