Hash of hash of list of lists in javascript - javascript

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

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"
]
]
}
}"

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 ] ] }

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.

Related

Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)

object identifications in javascript and restful service

Consider classes
Product = {
variations: [],
properties: []
}
Property = {
values: []
}
Variation = {
values: []
}
Value = {
simpleString:""
}
On the client (in JS) I first create products with properties and the possible values each property may have.
After that I create variations. Each of them can have a set of several values. But it only can "use" the values, which do already exist for properties.
In the next step, I move that product-object over to rest api.
While in JS the values used in a variation points to the original object in the product property, after encoding to JSON and backwarts to stdClass in PHP behind the restful service, this link gets lost.
Of course I could give them IDs on my own and call them temp_id or so. Hacky.
How would pros do it?
PHP
I simply deserialize the incomming JSON $object = json_decode($json); and use RedBeans and Piped to manage that end. What it does is mainly just moving through the properties and create objects with ..._id == null (then they get a unique ID).
Let's say I would do it manually:
I'd walk through the properties and store each value-object into the MySQL-db. Say
{
value_id: null,
simpleString: 'Green'
}
After storing it will have the value_id = 111.
Now I walk through the variations. One of these uses the Green-Value. But since this value will also be
{
value_id: null,
simpleString: 'Green'
}
how could I identify them? The string, of course, is too weak - no one could consider that. As mentioned above, I could give them temporary IDs. But surely there is a better way.

C# Dictionary equivalent in JavaScript

Is there exist any kind of c# dictionary in JavaScript. I've got an app in angularjs that requests data from an MVC Web Api and once it gets, it makes some changes to it. So the data is an array of objects, which is stored in the MVC Web Api as a Dictionary of objects, but I convert it to list before passing it throug network.
If I convert the Dictionary directly to JSon I get something like:
array = [ {Id:"1", {Id:"1", Name:"Kevin Shields"}},
{Id:"2", {Id:"2", Name:"Natasha Romanoff"}}
];
Well the objects are a little more complex, but you've got now an idea. The problem is that this format is even harder to operate with (I've got alphabetical keys or ids). So is there any equivalent to a dictionary? It's quite simple to do thing like:
Object o = dictionary["1"];
So that's it, thank in advance.
You have two options really, although both essentially do the same thing, it may be worth reading a bit more here, which talks about associative arrays (dictionaries), if you wish to tailor the solution:
var dictionary = new Array();
dictionary['key'] = 'value'
Alternatively:
var dict = [];
dict.push({
key: 'key',
value: 'value'
});
Update
Since ES2015 you can use Map():
const dict = new Map();
dict.set('{propertyName}', {propertyValue});
I know this question is a bit older, but in ES2015 there is a new data structure called map that is much more similar to a dictionary that you would use in C#. So now you don't have to fake one as an object, or as an array.
The MDN covers it pretty well. ES2015 Map
Yes, it's called an object. Object have keys and values just like C# dictonaries. Keys are always strings.
In your case the object would look like this:
{
"1": {
"Id": 1,
"Name":" Kevin Shields"
},
"2": {
"Id": 2,
"Name": "Natasha Romanoff"
}
}
The default ASP.net serializer produces ugly JSON. A better alternative would be Json.NET.
My Example:
var dict = new Array();
// add a key named id with value 111
dict.id = 111;
//change value of id
dict.id = "blablabla";
//another way
// add a key named name with value "myName"
dict["name"] = "myName";
//and delete
delete dict.id;
delete dict["name"]
//another way
dict = {
id: 111,
"name": "myName"
};
//And also another way create associate array
var myMap = { key: [ value1, value2 ] };

How are objects in JavaScript stored in memory?

On the official documentation of JSON
An object is an unordered set of name/value pairs. An object begins
with { (left brace) and ends with } (right brace). Each name is
followed by : (colon) and the name/value pairs are separated by ,
(comma).
Note
I am Javascript newbie, and from the name JSON (Javascript object notation) itself, I am assuming objects in Javascript are same as JSON. Please correct me in case I have got it wrong.
From the above definition it seems the Javascript objects are most probably implemented by either a hashmap or a BST or some similar data-structure.
But when I insert key value pairs in Node shell, they are inserted in serialised manner. This is what I tried in node shell
> var a = {}
undefined
> a['k1'] = 'a1'
'a1'
> a['k3'] = 'a3'
'a3'
> a['k2'] = 'a2'
'a2'
> a['k4'] = 'a4'
'a4'
> a['k5'] = 'a5'
'a5'
> a
{ k1: 'a1',
k3: 'a3',
k2: 'a2',
k4: 'a4',
k5: 'a5' }
Now, on printing a the key value pairs are returned in the same order as that of insertion. So my questions are:
Do I get fast lookups for a key? I mean complexity of O(log(n)) or better.
In case JSON is not using a data-structure like a BST, hashmap or some similar DS, then how exactly are JSON objects layed under the memory?
Update
Ok, so what about Javascript objects. Can someone comment on the underlying implementation of Javascript objects.
You're confusing JSON, which is only a text-based serialization format enabling simple data exchange, and plain javascript objects, which are unordered lists of properties.
As said by the MDN :
An object is a collection of properties, and a property is association
between a name and a value. A value of property can be a function,
which is then known as the object's method.
Objects properties can be seen as hash maps, as they're not ordered. But it's often a little more complicated : when objects are prototype based, properties not found on an object are searched upward the prototypes it's based on.
With javascript objects you get a guaranteed fast look-up, as this is an essential part of the implementation. But the implementation isn't defined by the norm and each engine can have its own.
Update
Starting from ES6, which you have in almost all browsers and JS servers in 2021, the order of non integer keys in object is the insertion order.

Javascript multi-dimensional array to and from JSON (jQuery?)

I have a Javascript problem where I need to be able to store data like follows:
MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..)
The main array has 10 sub arrays, these sub arrays then contain any number of JavaScript Objects.
I need an efficient way of storing the data this way and need to know how to parse to JSON/decode back to a manageable structure in Javascript.
The reason for this structure is because the Java program I'm communicating with uses this structure.
I'm able to use jQuery if that makes any difference.
Your structure appears to look like this
var myVariable = [
[
{ }, { }, { }
],
[
{ }, { }, { }
]
]
This can be JSON stringified. It yields "[[{},{},{}],[{},{},{}]]"
Use JSON.stringify and JSON.parse, respectively.

Categories

Resources