Home:ALL Converter>Javascript Path object path into a function and update object

Javascript Path object path into a function and update object

Ask Time:2015-02-09T02:35:47         Author:WABBIT0111

Json Formatter

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);

Author:WABBIT0111,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28397783/javascript-path-object-path-into-a-function-and-update-object
Aadit M Shah :

The problem is that stock.table.apple is not a reference. It is the value 5. Hence:\n\n change(stock.table.apple, -2)\n= change(5, -2)\n\n path = 5\n amount = -2\n\n path += amount\n\n path = 3\n amount = -2\n\n\nAs you can see, the path += amount changes the value of path and not the value of stock.table.apple.\n\nOne way to work around this is as follows:\n\n\r\n\r\nvar stock = {\r\n basket: {\r\n apple: 3,\r\n orange: 2\r\n },\r\n table: {\r\n apple: 5,\r\n orange: 5\r\n }\r\n};\r\n\r\nfunction change(object, key, amount) {\r\n object[key] += amount;\r\n}\r\n\r\nchange(stock.table, \"apple\", -2);\r\n\r\nalert(stock.table.apple);",
2015-02-08T18:50:16
Gennady :

function change(path, amount){\n var key = Object.keys(path)[0];\n path[key] += amount;\n}\n\n// calling function\nchange (stock.table,-2);\nconsole.log(stock.table.apple);\n\n\nyou can send only part for update",
2015-02-08T18:49:07
yy