1

I'm working on Javascript and want to pass a object path to the function and update the object. Why would the object not be updated? and is there a slick way of getting it to work besides returning, or besides passing the entire object to the function and specify the path inside? thx

var stock={
    basket:{
        apple:3,
        orange:2
    },
    table:{
        apple:5,
        orange:5
    }
};
function change(path, amount){
    path+=amount;
}

// calling function
change (stock.table.apple,-2);
console.log(stock.table.apple);
WABBIT0111
  • 2,233
  • 2
  • 18
  • 30
  • The stock.table.apple should update to 3 after calling the "change" function, but it's not updated, and shows 5 still. – WABBIT0111 Feb 08 '15 at 18:37

3 Answers3

0
function change(path, amount){
    var key = Object.keys(path)[0];
    path[key] += amount;
}

// calling function
change (stock.table,-2);
console.log(stock.table.apple);

you can send only part for update

Gennady
  • 26
  • 2
  • A hack like `Object.keys(path)[0]` is not a very good solution. You shouldn't rely on the object key order: http://stackoverflow.com/q/9179680/783743 – Aadit M Shah Feb 08 '15 at 18:53
0

This one was tricky. You are calling change function with the value stored in the stock.table.apple, not the actual path.

Your function call is change(5, -2).

You can pass an object reference + path as a string:

change(stock, "table.apple", -2) // look for attributes of the stock object

or the whole path as a string, like:

change("stock.table.apple", -2) // look for attributes of the window object
Jay
  • 3,445
  • 2
  • 24
  • 29
0

The problem is that stock.table.apple is not a reference. It is the value 5. Hence:

  change(stock.table.apple, -2)
= change(5,                 -2)

    path   = 5
    amount = -2

    path += amount

        path   = 3
        amount = -2

As you can see, the path += amount changes the value of path and not the value of stock.table.apple.

One way to work around this is as follows:

var stock = {
    basket: {
        apple:  3,
        orange: 2
    },
    table: {
        apple:  5,
        orange: 5
    }
};

function change(object, key, amount) {
    object[key] += amount;
}

change(stock.table, "apple", -2);

alert(stock.table.apple);

The above code works because stock.table is a reference value. The following answer will help you understand the difference between reference values and primitive values:

Primitive value vs Reference value

Hope that helps.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299