0

Testing my ability to write code in JavaScript and Node (perhaps a bit of a monumental effort) and also attempting to understand standards.

I want to dynamically change an attribute in an object as in this examnple:

    var parms = {
        host:'',
        port:'',
        user:'',
        pass:''
    };
    
    parms.user='foo';
    parms.pass='bar';
    console.log(parms.user);
    setParm = function(param,value){
        parms.param = value;
    }
    
    setParm('user','baz');
    console.log(parms.user);

However, I'm completely blind. I feel as though I may be in a blind alley in terms of what I think is possible versus what is actually workable.

cs95
  • 379,657
  • 97
  • 704
  • 746
Ken Ingram
  • 1,538
  • 5
  • 27
  • 52
  • 2
    I think you need `parms[param] = value;` – cs95 Jul 29 '17 at 00:17
  • Ahhhhhh! Yes. That was it. Fundamentals. – Ken Ingram Jul 29 '17 at 00:19
  • I'm a basic learner myself. But I'm glad I could help :) – cs95 Jul 29 '17 at 00:20
  • See [*MDN Property accessors*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors). – RobG Jul 29 '17 at 00:31
  • you should be using getters and setters instead... – Bekim Bacaj Jul 29 '17 at 00:36
  • @BekimBacaj—that's a red herring. The OP wants to know how to access a property using the value of a variable. [Setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) and [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) don't help with that, they're a completely different concept. – RobG Jul 29 '17 at 00:45
  • 1
    @kenIngram: you seem to want to learn the fundamentals, so although not explicitly asked let me recommend these online and free books. http://eloquentjavascript.net/ (beginner) , https://github.com/getify/You-Dont-Know-JS (intermediate / advanced) . Takes a couple of weeks but this is (arguably) the best stuff that's out there. Good luck! – Geert-Jan Jul 29 '17 at 00:48
  • Thanks. I did Codeschool a while back and alot of it got in, but not much stuck. Also, this question arose because I was working on creating getters and setters. – Ken Ingram Jul 29 '17 at 05:25
  • @RobG Don't they, really?!! – Bekim Bacaj Jul 29 '17 at 23:02
  • No. Getters and Setters do not answer my question. – Ken Ingram Jul 31 '17 at 04:46
  • @KenIngram Remember you can accept a solution if it answered your question! – cs95 Jul 31 '17 at 13:13

1 Answers1

1

You are passing the property as a string, so accessing with . won't work. One solution I know is that you can use dict-like indexing:

    var parms = {
        host:'',
        port:'',
        user:'',
        pass:''
    };
    
    parms.user='foo';
    parms.pass='bar';
    console.log(parms.user);
    setParm = function(param,value){
        parms[param] = value;
    }
    
    setParm('user','baz');
    console.log(parms.user);
cs95
  • 379,657
  • 97
  • 704
  • 746