Reputation: 4460
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.
Upvotes: 4
Views: 6067
Reputation: 87203
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.
@
symbol=
symbol to get the key and valuemyObj[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
Upvotes: 3
Reputation: 1395
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.
Upvotes: 2