12

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

2 Answers 2

18
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.

Sign up to request clarification or add additional context in comments.

6 Comments

@Stephen myMap = {} reset it to an empty map.
how can you remove a specific element?
tf is dataSource.get? Non-ECMA.
how do I check if myMap has keys or is empty?
@dierre var isEmpty = Object.keys(myMap).length === 0
|
8

Dynamic values and keys can be added using this notation:

var myMap = {}; // Create empty map
myMap["some" + "dynamic" + "key"] = "some" + "dynamic" + "variable";

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.