javascript - Variables names to access nested object keys -


this question has answer here:

apologies if title makes no sense, couldn't find way describe this. have searched lot keep getting answers access single level.

i have object:

var o = {     id: 1,     customer: {         name: 'barry scroggins'     } } 

i have accessor:

var keyname = 'customer' 

which know can use in following way customer part of object:

o[keyname] // { name: 'barry scroggins' } 

however, in application, access 'name' portion of customer object, using dynamically created set of variables. application churns out string:

var accessors = 'customer.name'; 

which split @ '.' array of entries, no matter try, can't access customer name part directly.

i know can this: o['customer']['name'] need build keys dynamically , there number of levels them (i.e. customer.address.zipcode)

is possible, or terrible, horrible way build things? if so, have alternative?

you split path , reduce object.

function getvalue(o, path) {      return path.split('.').reduce(function (o, k) {          return (o || {})[k];      }, o);  }    var o = {          id: 1,          customer: {              name: 'barry scroggins'          }      },      accessors = 'customer.name';    console.log(getvalue(o, accessors));


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -