2

I'm a perl programmer learning javascript. In perl, I would frequently use hashes to create 'data structures' from data returned from a database query. For example, I would build hashes like this:

*loop through list of data*
    push(@{$hash{$key1}{$key2}}, [$value1, $value2, $value3, $value4]);
*endloop*

this would add a reference to the list of four values to a list in the hash (with multiple keys).

I'm having a hard time finding information on how I would implement a similar structure in javascript. My goal is to read in a JSON file that has a list of objects (which has no particular order) and turn it into a hash so it can be sorted by the keys and then display it in an HTML table.

Perhaps this is the wrong way to think about this problem and javascript will have a different approach. I'd like to know if what I'm trying to do is possible, the code to create the hash, and the code to access the hash.

Thanks, Rob

Rob-0
  • 21
  • 1
  • 2

3 Answers3

2

This is my straight translation, tested at the Google Chrome console prompt >

> hash = {}
Object {}

> hash["key1"] = {}
Object {}

> hash["key1"]["key2"] = []
[]

> hash["key1"]["key2"].push([ 'value1', 'value2', 'value3', 'value4'])
1

> hash
Object {key1: Object}

> JSON.stringify(hash, null, 2)
"{
  "key1": {
    "key2": [
      [
        "value1",
        "value2",
        "value3",
        "value4"
      ]
    ]
  }
}"
stackunderflow
  • 953
  • 7
  • 17
1

Javascript does not have an ordered hash and a lookup with multiple keys. You can use the properties of an object to create a lookup by a single unique key and you can then build on that notion as needed. See this answer for an idea how to implement a simple form of hash or set in javascript.

The basic idea is that you create an object and then add key/value pairs to it:

var myLookup = {};
myLookup[key1] = value1;
myLookup[key2] = value2;

Then, you can look up a value by the key:

console.log(myLookup[key1]);    // shows value1

If you want more specific help, you will have to be more specific in your question. Show us what the JSON you start with and describe exactly how you want to be able to access it so we can figure out what type of JS data structure makes the most sense to put it in. Remember, once the JSON is parsed, it is already in a javascript data structure at that point so the it becomes a question of what kind of access you need to make to the data to understand whether the data should be restructured with certain key lookups?

It is generally best to concentrate on problem/solution and NOT on trying to do something the same way another language does it.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Hash in Perl is just set of key/value pairs. Javascript has similar data structure - Objects. You could do what you want

> a = {}
{}
> a.res = []
[]
> a.res.push([1,2,3])
1
> a.res.push([3,"sd",1])
2
> a
{ res: 
   [ [ 1, 2, 3 ],
     [ 3, 'sd', 1 ] ] }