2

I want to initiate the jquery-function "init" with an Object.The Object is predefined like

name={a:'d',b:'e',c:'f'}     

. The name of the Object is the html-id from the svg-rect-Object I clicked.

This is what I have. The Problem is, that "nameofrect" when called gives back a String not the Object. What can I do?

$(document).on('click', '.some-svg-rect', function () {
        var nameofrect = ((this.id).slice(1)).toLowerCase(); `//normal id = 'r'+somename`
        init(nameofrect);
    });
zeedi
  • 21
  • 1
  • I'm guessing you're looking for http://stackoverflow.com/questions/10976897/converting-a-string-to-json-object? – bbill Jul 28 '15 at 15:08
  • I´m not sure. If i try init(JSON.parse(nameofrect)); I get "Uncaught SyntaxError: Unexpected token" + "first char of the string". – zeedi Jul 28 '15 at 15:28
  • I'm not entirely clear on your question. What is `nameofrect`? Something like `"+name={a:'d',b:'e',c:'f'}"`? Also, it's worrying me that you seem to be using an HTML element's ID attribute to store JSON data that's not in a valid format - is that exactly what the `name` string is? If so, is that something you can change? – bbill Jul 28 '15 at 15:59
  • I have the JSON objects: `code`name1 = {..}, name2 = {..}, ...; I have some svg-rects: `code`'' To start init(nameofrect) I extract the rect-id as you see above. This id is the same like name1 or 2.. Instead of the (name1 or 2.. )-object I only get the String of the extractet id. – zeedi Jul 28 '15 at 16:32

1 Answers1

0

Here's what you could do.

var names = {
  name1: {a:'d',b:'e',c:'f'} 
  , name2: {} //etc
}

var nameObj = names[((this.id).slice(1)).toLowerCase()] //this is the object you wanted

You were asking about referencing a global variable by its string name, basically. Is there a way to access a javascript variable using a string that contains the name of the variable?

You can just use the window variable without making the names object but I don't recommend that. (Get global variable dynamically by name string in JavaScript)

Community
  • 1
  • 1
bbill
  • 2,264
  • 1
  • 22
  • 28
  • Let me know if this doesn't work. And as I asked above, *please include an example value of what `nameofrect` is*. Ideally, `console.log` it and paste it here. – bbill Jul 28 '15 at 16:42
  • It doesn´t. `code`Uncaught SyntaxError: Unexpected token b(anonymous function) @ ThisisData.html:139m.event.dispatch @ jquery.js:4670m.event.add.r.handle @ jquery.js:4338`code` Examplevalue for nameofrect: "rabc" Examplevalue in script.js : abc = {name : 'alphabet',content : ['a','j','z']} – zeedi Jul 28 '15 at 17:03
  • Ohh see debug output makes everything 100% clear. I've updated my answer. Sorry it took a while, been looking at a lot of code. – bbill Jul 28 '15 at 17:31