Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store integers as keys in a javascript object?

I'm creating an index file in JSON, which I'm using as a sort-of-database index for a javascript application I'm working on.

My index will look like this:

{
"_id": "acomplex_indices.json",
"indexAB": {
    "title": {
        "Shawshank Redemption": [
            "0"
        ],
        "Godfather": [
            "1"
        ],
        "Godfather 2": [
            "2"
        ],
        "Pulp Fiction": [
            "3"
        ],
        "The Good, The Bad and The Ugly": [
            "4"
        ],
        "12 Angry Men": [
            "5"
        ],
        "The Dark Knight": [
            "6"
        ],
        "Schindlers List": [
            "7"
        ],
        "Lord of the Rings - Return of the King": [
            "8"
        ],
        "Fight Club": [
            "9"
        ],
        "Star Wars Episode V": [
            "10"
        ],
        "Lord Of the Rings - Fellowship of the Ring": [
            "11"
        ],
        "One flew over the Cuckoo's Nest": [
            "12"
        ],
        "Inception": [
            "13"
        ],
        "Godfellas": [
            "14"
        ]
    },
    "year": {
        "1994": [
            "0",
            "3"
        ],
        "1972": [
            "1"
        ],
        "1974": [
            "2"
        ],
        "1966": [
            "4"
        ],
        "1957": [
            "5"
        ],
        "2008": [
            "6"
        ],
        "1993": [
            "7"
        ],
        "2003": [
            "8"
        ],
        "1999": [
            "9"
        ],
        "1980": [
            "10"
        ],
        "2001": [
            "11"
        ],
        "1975": [
            "12"
        ],
        "2010": [
            "13"
        ],
        "1990": [
            "14"
        ]
    }
}
}

So for every keyword (like Pulp Fiction), I'm storing the matching document-id(s).

My problem is with integers/numbers/non-string data, like the release year in the above example. This is stored as a string, while I had hoped it would be stored as a number.

I'm creating the index entries like this:

// indices = the current index file
// doc = the document to update the index with
// priv.indices = all indices defined for this application instance
// priv.indices.fields = index fields e.g. "year", "director", "title"
// priv.indices.name = name of this index

priv.updateIndices = function (indices, doc) {
var i, j, index, value, label, key, l = priv.indices.length;

// loop all indices to add document
for (i = 0; i < l; i += 1) {
  index = {};
  index.reference = priv.indices[i];
  index.reference_size = index.reference.fields.length;
  index.current = indices[index.reference.name];

  for (j = 0; j < index.reference_size; j += 1) {
    label = index.reference.fields[j];    // like "year"
    value = doc[label];                   // like 1985

    // if document has a label field (e.g. doc.year = 1985)
    if (value !== undefined) {

      // check if the index file already contains an entry for 1985
      index.current_size = priv.getObjectSize(index.current[label]);

      if (index.current_size > 0) {
        // check if the document id is already in the index
        // in case the data is updated (e.g. change 1982 to 1985)
        key = priv.searchIndexByValue(
          index.current[label],
          doc._id,
          "key"
        );
        if (!!key) {
          delete index.current[label][key];
        }
      }
      // create a new array if 1985 is not in the index yet
      if (index.current[label][value] === undefined) {
        index.current[label][value] = [];
      }
      // add the document id to an existing entry
      index.current[label][value].push(doc._id);
    }
  }
}
return indices;

};

This works fine, except that fields I want to store as non-strings (integers, numbers or datetime), like the year in the above example end up as strings in my index.

Question:
Is it at all possible to store "non-string" types in a JSON document? If so, can I also store the key of a key/value pair as a "non-string" element.

If not, would I have to add a parameter to my index definitions declaring the type of each key in order to modify the key-string when I run into it or is there a better way to do it?

Thanks!

like image 905
frequent Avatar asked Feb 04 '13 13:02

frequent


People also ask

Can JS object have int as key?

Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.

Can objects be keys in JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.

Can we get key from value in JavaScript?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.

Can a JavaScript object key Be a string?

JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).


1 Answers

Is it at all possible to store "non-string" types in a JSON document?

Yes. The value of a property can be a string, number, boolean, object, array or null (undefined is a notable exception - it's a native JavaScript type but it's not a valid JSON value).

Can I also store the key of a key/value pair as a "non-string" element?

No. The key name must always be a string. However, that doesn't mean you can't parse that string into some other JavaScript type. For example, if you have a string but need a number, you can use the parseInt function, or the unary + operator.

See the JSON grammar for more detail.

like image 160
James Allardice Avatar answered Sep 26 '22 16:09

James Allardice