HashMap example in JavaScript -


i have string below.

10=150~jude|120~john|100~paul@20=150~jude|440~niroshan@15=111~eminem|2123~sarah 

i need way retrieve string giving id.

e.g.: give 20; return 150~jude|440~niroshan.

i think need hashmap achieve this.

key > 20

value > 150~jude|440~niroshan

i looking pure javascript approach. appreciated.

if you're getting above string in response server, it'll better if can in below object format in json format. if don't have control on how you're getting response can use string , array methods convert string object.

creating object better choice in case.

  1. split string @ symbol
  2. loop on substrings splitted array
  3. in each iteration, again split string = symbol key , value
  4. add key-value pair in object
  5. to value 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 @ symbol , iterate on each item array  str.split('@').foreach(function(e) {    var arr = e.split('=');      hashmap[arr[0]] = arr[1]; // add key value in object  });    console.log(hashmap);    document.write(hashmap[20]); // access value using key


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -