Source: DYNAMICALLY Accessing nested JavaScript objects and arrays by string path et un petit jsFiddle pour la route.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Object.byString = function(o, s) { s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); for (var i = 0, n = a.length; i < n; ++i) { var k = a[i]; if (k in o) { o = o[k]; } else { return; } } return o; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const priceTable = { "<=4": { "size": [ { "100": "5.11", "250": "4.62", "500": "4.04", "1000": "3.81", "2000": "3.60" }, { "100": "5.11", "250": "4.62", "500": "4.04", "1000": "3.81", "2000": "3.60" }, { "100": "5.11", "250": "4.62", "500": "4.04", "1000": "3.81", "2000": "3.60" }, { "100": "5.11", "250": "4.62", "500": "4.04", "1000": "3.81", "2000": "3.60" }, { "100": "5.11", "250": "4.62", "500": "4.04", "1000": "3.81", "2000": "3.60" }, // <=4.size[4]['2000'] = 3.60 { "100": "5.88", "250": "4.88", "500": "4.88", "1000": "3.88", "2000": "3.88" } ] } } const combinedPath = buildPath( $_THIS ) + "." + matchingThreshold; // PAS interprété comme une chaîne de caractères const targetValue = Object.byString( priceTable, combinedPath ); // interprété comme une chaîne de caractères (<=4.size[4]['2000']) |