Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrectly returning an Object?

I have a following function that looks like this:

    function addProperty(object, property) {

}

I have to add the value of the property argument as a key to the object argument. The value of the new property must be set to null. After that, i will return the object with the newly added property to it. The expected input is something like this: { x: 5 }, 'y' with the object to the left and property on the right. The expected output is this: { x: 5, y: null }.

This is what i have so far:

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

addProperty({x:5}, 'y');

This is the output i get: { object: { x: 5 }, y: null }. What am i doing wrong here? how do i get rid of what looks like an object property at the beginning of the output and leave the object itself and the property??.

like image 499
Erick Ramirez Avatar asked Dec 11 '25 14:12

Erick Ramirez


2 Answers

Use Object#assign to create a new object based on the original, with the new property:

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

console.log(addProperty({x:5}, 'y'));

Or use the Object Rest/Spread proposal (requires Babel and the transform):

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

console.log(addProperty({x:5}, 'y'));

What's wrong with your code:

When you write { object }, you are using ES6 Shorthand property names to create a new object literal, that has the property "object", with the old object's value. Effectively you are writing:

object = { object: object }

function addProperty(object, property) {
  object = { // assign a new object literal to the object variable
    object, // add a new property by name of "object" with the contents of the original object
    [property]: null
  };
  return object;
}

console.log(addProperty({x:5}, 'y'));
like image 71
Ori Drori Avatar answered Dec 14 '25 05:12

Ori Drori


Set object property like this :

function addProperty(object, property) {
  object[property] =  null;
  return object;
}
like image 31
agit Avatar answered Dec 14 '25 04:12

agit