最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative to es6 Map - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked Apr 10, 2017 at 8:30 BazBaz 13.2k40 gold badges152 silver badges279 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论