'Alternative to es6 Map
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | baao |
| Solution 2 | Parameshwar |
