javascript - Find object by properties from array -


with array, value, , and object nested objects:

object

mesh 

array

['options', 'range', 'x'] 

value

12.5 

is possible translate update property, e.g.

mesh.options.range.x = 12.5 

attempted:

index = (obj, i) ->    obj[i]  arr.reduce(index, obj) = 12.5 

update

thank elegant solutions.

using .reduce() pretty nice this:

// current object----|    |----current key //                   v    v arr.reduce(function(obj, key) {     return obj == null ? obj : obj[key]; }, window.mesh); //        ^ //        |-- initial object 

your attempt use .reduce() needed pass function manages "accumulation".

here, long previous obj wasn't null or undefined, it'll return key of current obj, becomes next obj.


then since need assign value, you'd want value of second last key.

var o = arr.slice(0,-1).reduce(function(obj, key) {     return obj == null ? obj : obj[key]; }, window.mesh); 

and check existence , use last item in arr assignment.

o && o[arr.pop()] = 12.5; 

all of can abstracted away function 1 or other based on how many arguments passed.

function setfromarray(obj, arr, val) {     var keys = arguments.length < 3 ? arr.slice() : arr.slice(0, -1);      var o = keys.slice(0,-1).reduce(function(obj, key) {         return obj == null ? obj : obj[key];     }, window.mesh);      if (arguments.length < 3)         return o;     else          o && o[keys.pop()]; } 

Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -