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??.
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'));
Set object property like this :
function addProperty(object, property) {
object[property] = null;
return object;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With