Koen H
Koen H

Reputation: 111

How to use a var to look up and change a Object Property

I'm looking for a way to use a string as a lookup in an Object. Here is my code:

$.extend(true, myOptions,{ series: {lines: {show: true} } } );

The lines property could also be one of these:

  • bars
  • points

    I have created a form where you can choose between those three options
    So the property lines need to be a variable

    $.extend(true, myOptions,{ series: {VARIABLE: {show: true} } } );   
    

    How do I do that?

    Upvotes: 0

    Views: 36

  • Answers (2)

    Jonathan Lonowski
    Jonathan Lonowski

    Reputation: 123473

    Object literals/initialisers don't support using variables as keys. Any identifiers used on the left of a : will be taken just for their name.

    So, you'll have to break it out into multiple steps and use bracket notation to have a VARIABLE key.

    var input = { series: {} };
    input.series[VARIABLE] = { show: true };
    
    $.extend(true, myOptions, input);
    

    Upvotes: 1

    Michael Krelin - hacker
    Michael Krelin - hacker

    Reputation: 143119

    Your wording is confusing, but if you want to access object properties with the name stored in variable you can do it like obj[var].

    Upvotes: 0

    Related Questions