1

Apologies if this title makes no sense, but I couldn't find a way to describe this. I have searched a lot but keep getting answers to access a single level.

I have an object:

var o = {
    id: 1,
    customer: {
        name: 'Barry Scroggins'
    }
}

I have an accessor:

var keyName = 'customer'

Which I know I can use in the following way to get the customer part of the object:

o[keyName] // { name: 'Barry Scroggins' }

However, in my application, I would like to access the 'name' portion of the customer object, using a dynamically created set of variables. So my application churns out this string:

var accessors = 'customer.name';

Which I then split at the '.' to get an array of entries, but no matter what I try, I can't access the customer name part directly.

I know I can do it like this: o['customer']['name'] but I need to build up those keys dynamically and there could be any number of levels to them (i.e. customer.address.zipcode)

Is this possible, or is a terrible, horrible way to build things? If so, do you have an alternative?

Ben Harvey
  • 1,793
  • 2
  • 16
  • 23
  • Although possible, this is a terrible, horrible way to build things. Put everything in var customer, don't even create var o. Refer to Nina Scholz's answer for those who don't have a more reasonable alternative. The OP does have a better way available though. – TurnipEntropy Nov 10 '16 at 15:06
  • @TurnipEntropy I agree, the whole thing is a mess but almost everything is pooped out of a backend api then dumped into a single template which is used to render a webpage. Although a duplicate, I prefer the answer given below. – Ben Harvey Nov 10 '16 at 15:10

1 Answers1

3

You could split the path and reduce the 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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392