javascript2016 javascript2016 - 5 months ago 9
Javascript Question

How to change property values of object passed into a function?

I am trying to change the property values of an object I pass into my function. If object has the property (for example 'stuff' it should change its value from some to'new value' - however my code doesn't work-could someone explain why its not working and how I can change the values?
Thank you!!

function changeProperties(obj) {
// var obj;
return function() {
//var properties=
for (var key in obj) {
if (arguments.length == 1) {
if (key == arguments[0]) {
return obj[key];
} else {

obj[key] = arguments[1];
return obj[key];
}
}
}
}
//return obj;
}

var obj = {
stuff: 'some'
};
var changing = changeProperties(obj);

changing('stuff', 'new value');
obj.stuff;

Answer

Your code doesn't work because you have the else nested incorrectly.

But more basically, there is no need to loop through properties. You can just say

function changeProperties(obj) {
    return function() {
        if (arguments.length === 2) obj[arguments[0]] = arguments[1];
        return obj[arguments[0]];
    };
}

Or perhaps more readably

function changeProperties(obj) {
    return function(key, val) {
      return val === undefined ? obj[key] : obj[key] = val;
    };
}