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

HashMap example in pure JavaScript - Stack Overflow

programmeradmin4浏览0评论

I have String like below.

10=150~Jude|120~John|100~Paul@20=150~Jude|440~Niroshan@15=111~Eminem|2123~Sarah

I need a way to retrieve the string by giving the ID.

E.g.: I give 20; return 150~Jude|440~Niroshan.

I think I need a HashMap to achieve this.

Key > 20

Value > 150~Jude|440~Niroshan

I am looking for an pure JavaScript approach. Any Help greatly appreciated.

I have String like below.

10=150~Jude|120~John|100~Paul@20=150~Jude|440~Niroshan@15=111~Eminem|2123~Sarah

I need a way to retrieve the string by giving the ID.

E.g.: I give 20; return 150~Jude|440~Niroshan.

I think I need a HashMap to achieve this.

Key > 20

Value > 150~Jude|440~Niroshan

I am looking for an pure JavaScript approach. Any Help greatly appreciated.

Share Improve this question edited Jun 12, 2018 at 5:25 Jude Niroshan asked Sep 21, 2015 at 10:14 Jude NiroshanJude Niroshan 4,4609 gold badges43 silver badges67 bronze badges 1
  • gist.github./StephanBijzitter/6706de176c5c1e4dc26d has 1 dependency, but it can easily be changed as it only uses the event handler for it – Stephan Bijzitter Commented Sep 21, 2015 at 10:17
Add a ment  | 

2 Answers 2

Reset to default 3

If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.

Creating an object is better choice in your case.

  1. Split the string by @ symbol
  2. Loop over all the substrings from splitted array
  3. In each iteration, again split the string by = symbol to get the key and value
  4. Add key-value pair in the object
  5. To get the value from object using key use array subscript notation e.g. myObj[name]

var str = '10=150~Jude|120~John|100~Paul@20=150~Jude|440~Niroshan@15=111~Eminem|2123~Sarah';

var hashMap = {}; // Declare empty object

// Split by @ symbol and iterate over each item from array
str.split('@').forEach(function(e) {
  var arr = e.split('=');

  hashMap[arr[0]] = arr[1]; // Add key value in the object
});

console.log(hashMap);

document.write(hashMap[20]); // To access the value using key

If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.

发布评论

评论列表(0)

  1. 暂无评论