-1

I'm having an issue. I want to have a static dict

var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };

There are a lot of entries, and I want to have an easy access to all of them in case I need to change their value. Because of this, I don't like the single-line declaration.

As an alternative, I did manage to do the following, since multi-line text is allowed in Javascript:

var dict = {};
var loadDict = function() {

    text = "aaa,true\n\
aab,false\n\
aac,false\n\
aad,true\n\[...]";

    var words = text.split( "\n" );
    for ( var i = 0; i < words.length; i++ ) {
        var pair = words[i].split(",");
        dict[ pair[0].trim() ] = pair[1].trim();
    }   
}

Is there a better/more elegant way of having a multi-line declaration of a dict?

note: Creating multiline strings in JavaScript is a solution only for strings. it doesn't work with a dict.

edit: I was adding a '\' at the end of each line. That was the issue. thanks.

Community
  • 1
  • 1
iliaden
  • 3,791
  • 8
  • 38
  • 50

3 Answers3

3
var myDict = {
    "aaa": true,
    "aab": false,
    "aac": false,
    "aad": true,
    [...]
};

I hope this is what you meant, because it's basic Javascript syntax.

Also, if for some reasons you want to "store" simple objects (made of strings, numbers, booleans, arrays or objects of the above entities) into strings, you can consider JSON:

var myDictJSON = '{\
    "aaa": true,\
    "aab": false,\
    "aac": false,\
    "aad": true,\
    [...]
}';
var myDict = JSON.parse(myDictJSON);

Support for JSON is native for all the major browsers, including IE since version 8. For the others, there's this common library json2.js that does the trick.

You can also convert your simple objects into string using JSON.stringify.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
1

that's easy-

var myDict={
  "aaa":true,
  "aab":false,
  "aac":false,
  "aad":true
};

please remember, don't place the curly bracket in the next line.

i like responses. Please respond

Ash
  • 3,431
  • 2
  • 15
  • 15
0

This (a complex data structure containing both "string" and "booleans"):

var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };

Can be expressed like this:

var myDict={
  "aaa":true,
  "aab":false,
  "aac":false,
  "aad":true, 
  [...] 
};

Similarly, this:

  var myBigHairyString = "Supercalifragilsticexpialidocious";

Can be expressed like this:

  var myBigHairyString = 
    "Super" +
    "califragilstic" +
    "expialidocious";
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • String splitting like that can be good for code indentation, but it's slower because JS operations on strings are actually executed. – MaxArt Jun 12 '12 at 21:54