4

I am trying to figure out how to do an C# "function" in javascript but am having no luck!?

Here is the C#:

var parameters = new Dictionary<string,string>
{
    { "link", "http://mysite.com" },
    { "name", "This is an test" }
};

I want to think that I have to use "new Array" but am not sure how to do this?

Any help is appreciated and thanks in advance :-)

1
  • What are you trying to achieve here? You can't use .NET classes in JavaScript, so your question looks strange. Commented Aug 28, 2013 at 14:23

5 Answers 5

3

Here is a great explanation: JavaScript Associative Arrays Demystified

var parameters = new Array();
parameters['link'] = 'http://mysite.com';
parameters['name'] = 'This is an test';
Sign up to request clarification or add additional context in comments.

Comments

3

In JavaScript, every object is a dictionary (an associative array). Your example can be written as an object literal:

var parameters = {
  link: "http://mysite.com",
  name: "This is an test"
};

// Read access
console.log(parameters.link); // or:
console.log(parameters["link"]);

// Write access
parameters.link = "http://yoursite.com"; // or:
parameters["link"] = "http://yoursite.com";
parameters.status = "OK"; // or:
parameters["status"] = "OK";

This example shows that the values (field values) of the dictionary (object) are usually accessed by writing the key (field name) using dot notation, but you can also use the index notation, as in case of C# dictionaries. Note that JavaScript is a dynamic language, so the type of keys and values can be anything. So you can define a dictionary (object) like this one:

var parameters = {
  link: "http://mysite.com",
  name: "This is an test",
  id: 3,
  4: "$#!+",
  5: 123456
};

The values (field values) can be other objects or functions, too. If a value is a function, it is called a method of the JavaScript object.

=== UPDATE ===

Here is an approximation of the C# Dictionary<TKey,TValue> class in JavaScript (the test page is here). This code works, but I strongly recommend doing things in JavaScript the JavaScript way: objects can be used directly as associative arrays, there is no real need to use such a wrapper!

var Dictionary = (function () {
    function Dictionary() {
        if (!(this instanceof Dictionary))
            return new Dictionary();
    }

    Dictionary.prototype.Count = function() {
        var key,
            count = 0;

        for (key in this) {
            if (this.hasOwnProperty(key))
                count += 1;
        }
        return count;
    };

    Dictionary.prototype.Keys = function() {
        var key,
            keys = [];

        for (key in this) {
            if (this.hasOwnProperty(key))
                keys.push(key);
        }
        return keys;
    };

    Dictionary.prototype.Values = function() {
        var key,
            values = [];

        for (key in this) {
            if (this.hasOwnProperty(key))
                values.push(this[key]);
        }
        return values;
    };

    Dictionary.prototype.KeyValuePairs = function() {
        var key,
            keyValuePairs = [];

        for (key in this) {
            if (this.hasOwnProperty(key))
                keyValuePairs.push({
                    Key: key, 
                    Value: this[key]
                });
        }
        return keyValuePairs;
    };

    Dictionary.prototype.Add = function(key, value) {
        this[key] = value;
    }

    Dictionary.prototype.Clear = function() {
        var key,
            dummy;

        for (key in this) {
            if (this.hasOwnProperty(key))
                dummy = delete this[key];
        }
    }

    Dictionary.prototype.ContainsKey = function(key) {
        return this.hasOwnProperty(key);
    }

    Dictionary.prototype.ContainsValue = function(value) {
        var key;

        for (key in this) {
            if (this.hasOwnProperty(key) && this[key] === value)
                return true;
        }
        return false;
    }

    Dictionary.prototype.Remove = function(key) {
        var dummy;

        if (this.hasOwnProperty(key)) {
            dummy = delete this[key];
            return true;
        } else 
            return false;
    }

    return Dictionary;
}());

Test code:

var d = new Dictionary(),
    i,
    keyValuePair;

console.clear();

// Adding new elements.
d.Add("key1", "value1");
d.Add("key2", "value2");

// This also works. There is no KeyNotFoundException, 
// the key-value pairs are inserted silently.
d["key3"] = "value3";
d["key4"] = "value4";

// Getting the number of key-value pairs.
console.log("Count:", d.Count());

// Getting an array containing the keys.
console.log("Keys:", d.Keys());

// Getting an array containing the values.
console.log("Values:", d.Values());

// Iterating over the key-value pairs.
for (i = 0; i < d.KeyValuePairs().length; i += 1) {
    keyValuePair = d.KeyValuePairs()[i];
    console.log("#", i + 1, keyValuePair.Key, "=>", keyValuePair.Value);
}

// Determining whether the dictionary contains a given key.
console.log("key2?", d.ContainsKey("key2"));
console.log("keyhole?", d.ContainsKey("keyhole"));

// Determining whether the dictionary contains a given value.
console.log("value2?", d.ContainsValue("value2"));
console.log("valuable?", d.ContainsValue("valuable"));

// Removing a value with a given key.
console.log("Removing key2:", d.Remove("key2"));
console.log("Count after Remove():", d.Count());
console.log("Removing keyhole:", d.Remove("keyhole"));
console.log("Count after Remove():", d.Count());

// Clearing all key-value pairs.
d.Clear();
console.log("Count after Clear():", d.Count());

Console output (press F12):

Count: 4
Keys: ["key1", "key2", "key3", "key4"]
Values: ["value1", "value2", "value3", "value4"]
# 1 key1 => value1
# 2 key2 => value2
# 3 key3 => value3
# 4 key4 => value4
key2? true
keyhole? false
value2? true
valuable? false
Removing key2: true
Count after Remove(): 3
Removing keyhole: false
Count after Remove(): 3
Count after Clear(): 0 

1 Comment

I have tried all the above, but I need it to be {string,string}. How do i do that?
1

How about trying like this:-

var dict = []; 

dict.push({
    key:   "Yourkeyvalue",
    value: "value"
});

6 Comments

I thought to create two object literals in an array which have properties!!! Am I on the wrong track???
No, this is fine. This or an associative array is great, though it would be helpful for Mansa if you had explained WHY it would work
Well Javascript does not have associative arrays, it has objects. And arrays are also objects!!!! :) Hope that makes sense to Mansa ;)
This is not equivalent with the OP's C# example. This code create an array with one element, which is an object. There is no need to put the object into an array, it's equivalent with a C# Dictionary itself.
My problem is that it should return {string,string} and doesn't do so now?
|
1

Just use an object:

var parameters = {
    "link": "http://mysite.com",
    "name": "This is an test"
};

Comments

0

Here you go (off the top of my head so don't blame me for syntax errors if any come up).

This is an exact same approach as you would have done in C# so I think you are looking for this.

var parameters = [
    {
        key: 'link',
        value: 'http://mysite.com'
    },
    {
        key: 'name',
        value: 'This is an test'
    }];

or here is an alternative (might prefer it, depending on your coding style)

Create an array and add the items in after.

var parameters = [];
parameters.push(
    {
        key: 'link',
        value: 'http://mysite.com'
    },
    {
        key: 'name',
        value: 'This is an test'
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.