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
2 Answers
Reset to default 3If 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.
- Split the string by
@
symbol - Loop over all the substrings from splitted array
- In each iteration, again split the string by
=
symbol to get the key and value - Add key-value pair in the object
- 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.