0

Sorry for the basic question - this is a simplified version of much larger code which I cannot seem to solve this issue -

I have a JS created blog, im storing my blog details in a object and populating the HTML with those details, this lets me keep to DRY principle.

The issue I have found is that I cannot seem to use variables to complete a Objects path -

Create the Object >>

var objectExample = {

    one: [{

        method: function(x,y){
            console.log(`${x} ${y}`);
        }

    }]

}


var blockThing = document.querySelector('.block');

var name = 'one';
var sign = 0;

x = 'something new';
y = 'another new thing';

blockThing.addEventListener('click', function(){
    objectExample.name[sign].method(x,y);
});

I'm not sure why the above does not work as if I were to write

blockThing.addEventListener('click', function(){
        objectExample.one[0].method(x,y);
    });

i.e. not using variables - then it does work.

Please excuse me if this is a super basic question, I've been trying to resolve this is my larger example for an embarrassing amount of hours now.

Thank you for any help

Wally
  • 705
  • 1
  • 9
  • 24
  • `objectExample.name` doesn't work because `objectExample` has no `name` property. The reason `objectExample.one` *does* work is because there is in fact a `one` property. – mario_sunny Nov 04 '19 at 17:58
  • It's `objectExample[name]` if you want `name` to be evaluated as an expression (to get its value) instead of as the property name "name". – Pointy Nov 04 '19 at 17:58
  • ... and note that your code *already does that* with the variable `sign`! – Pointy Nov 04 '19 at 17:59
  • Thank you for the replies, yes, I missed the [xxx], sadly I did already know that (just made a spelling mistake) this is not the case with the larger code block, however does mean that the fault seems to be lying with my variables or variable scope... – Wally Nov 04 '19 at 21:22
  • After a decent night sleep and mulling over this I found the issue - I was using a loop to iterate over each blog post - In the object's path I needed to define [i] as let not as var...... and now a new journey of discovering why is born.... – Wally Nov 05 '19 at 07:54

0 Answers0