Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic Map key in javascript?

I have tried to create a map like example below...

var myMap= {"one": 1,"two": "two","three": 3.0};

So, I iterate them like:

for (var key in myMap) {

window.alert("myMapmap property \"" + key + "\" = " + myMap[key]);

}

If my data is dynamic... and I want to add each of them in to map... how the codes should be like? And I expect the key is not static...I mean the data taken from other source like database, that wasn't define before..

Thanks before

like image 639
Sthepen Avatar asked Mar 28 '11 07:03

Sthepen


People also ask

How do you create a dynamic key for an object?

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature. The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.

What is a dynamic key?

Dynamic keys are one-time symmetric cryptographic keys. forming a sequence of keys. Similar in nature to one- time pad, every message in the system is encrypted by a. different cryptographic key.

Can JavaScript Map have object as key?

A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.


2 Answers

Dynamic values and keys can be added using this notation:

var myMap = {}; // Create empty map
myMap["some" + "dynamic" + "key"] = "some" + "dynamic" + "variable";
like image 149
David Tang Avatar answered Sep 18 '22 15:09

David Tang


var dataSource = ...;
while (var o = dataSource.get()) {
     myMap[o.key] = o.value;
}

for (var key in myMap) {
     alert("key : " + key + " value : " + myMap[key]);
}

You can simply write to an object using array like syntax.

How and where you get your data is upto you.

like image 24
Raynos Avatar answered Sep 17 '22 15:09

Raynos