I'm wondering if the following can be done another way in javascript/es6:
var myMap = new Map();
myMap.set("id1", {"name": "John", "address":"near"} );
myMap.set("id2", {"name": "Úna", "address":"far away"} );
myMap.set("id2", {"name": "Úna", "address":"near"} );
I'm new to javascript and have read in Map's documentation that Objects have historically been used as Maps. Can the above been done using objects? I really don't like that I have to use set
and get
either.
I'm wondering if the following can be done another way in javascript/es6:
var myMap = new Map();
myMap.set("id1", {"name": "John", "address":"near"} );
myMap.set("id2", {"name": "Úna", "address":"far away"} );
myMap.set("id2", {"name": "Úna", "address":"near"} );
I'm new to javascript and have read in Map's documentation that Objects have historically been used as Maps. Can the above been done using objects? I really don't like that I have to use set
and get
either.
3 Answers
Reset to default 4As long as the key values are mere strings, you can just replace a Map with a plain object (You've already done that with the values you provided):
// init object
let myMap = {
"id1": {"name": "John", "address":"near"},
"id2": {"name": "Úna", "address":"far away"}
};
// add/replace
myMap.id2 = {"name": "Úna", "address":"near"};
// access
console.log( myMap.id2 );
The advantage of a Map is, that you can use arbitrary objects as a key value. In objects those would be converted to a string, which oftentimes does not result in a meaningful representation.
Following code helps to search and push data to object like map. But does accept duplicate key not as per map
const object1 = {
};
function pushit(keyStr,valStr,objectData)
{
objectData[keyStr] = valStr;
}
function searchPrint(keyStr)
{
if(object1.hasOwnProperty(keyStr))
{
console.log(object1[keyStr]);
}
}
pushit("sys msg" , "custom msg", object1);
pushit("sys msg1" , "custom msg1", object1);
pushit("sys msg2" , "custom msg2", object1);
searchPrint("sys msg2");
This is not an alternative for map but to store key and value and to search the same.
Of course you can, what you have is basically
let obj = {
id1: {"name": "John", "address":"near"},
id2: {"name": "Úna", "address":"far away"}
}
Note that, as well in the Map, and in the object too, the keys will override each other when setting a key twice. In strict mode, this would even be an error for the object.