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.
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.
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.
Related
replace() is not working on a variable I've created representative of a bunch of names I'm deriving from a JSON object in a loop.
I understand strings are immutable in JS. I believe I have ruled that out.
for (object in Object.keys(json)) {
console.log(json[object]["senderProfile"]["name"])
var name_ = String(json[object]["senderProfile"]["name"])
var name = name_.replace(',', '')
names.push(name+"<br>")
}
document.getElementById("json_out").innerHTML = names;
The HTML that is rendered has commas in between each name. Not sure what to make of it.
names is an array. You are implicitly converting the array to a string. By default, array members are separated by comma. Simple example:
console.log('' + [1,2,3])
You can join array members with a custom separator by calling .join:
console.log('' + [1,2,3].join(''))
It may be possible to simplify your code, but not without knowing what the value of json or json[object]["senderProfile"]["name"] is. However, instead of appending <br> to the name, you could use it as the element separator:
var names = Object.keys(json)
.map(key => json[key]["senderProfile"]["name"]);
document.getElementById("json_out").innerHTML = names.join('<br>');
Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();
The object value is something like this:
I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?
it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
obj.yourAttr == yourValue; });
this will give you a second array with the values found it. later, index the array for pick up the value do you need.
I'm learning Google Maps API; a call to its geolocation API returns a giant JSON string (sample: https://maps.googleapis.com/maps/api/geocode/json?address=66+Fort+Washington+Avenue+New+Yor,NY&key=AIzaSyAGLzbjA0rEl5whQgiuZZdIGVzPZzLv9Kg). If I'm looking for a particular key/value pair out of that resulting set of data to use in my Java script application, is it better to convert that JSON string into an object (parse) and then traverse that object for that key/value pair, or is it Ok just to traverse the returned JSON string itself? What are the pros/cons of each?
Parsing the JSON will always result in easier to read code and is less sensitive to changes in the data that you are receiving. However, if you are looking at pure performance it depends on how unique the data is that you are searching for in the returned JSON string, and how many searches you are doing. If you (for instance) just wanted the lat/long location from the returned string you mentioned above then you could do this:
var index = string.search("location");
var index2 = string.substring(index).search(/-?\d/); // finds first number
lat = parseFloat(string.substring(index+index2));
var index3 = string.substring(index+index2).search("lng");
var index4 = string.substring(index+index2+index3).search(/-?\d/); // finds first number
lon = parseFloat(string.substring(index+index2+index3+index4));
Or, by parsing it you could do this:
var obj = JSON.parse(string);
lat = obj.results[0].geometry.bounds.northeast.lat;
lon = obj.results[0].geometry.bounds.northeast.lon;
Clearly the parsed version is easier to read. However, I ran this 200000 times each, and found that the string search based approach was slightly more than 4 times faster than the JSON object parsing approach. There may have been other ways to optimize the search based approach but you get the idea.
You should use JSON.parse to turn your string into a JavaScript object before attempting to access its properties. You cannot "traverse the returned JSON string itself":
var json = '{ "property": "value" }'
// JSON strings cannot be traversed
console.log(typeof json) //=> "string"
console.log(json.property) //=> undefined
var object = JSON.parse(json)
// Objects can be traversed
console.log(typeof object) //=> "object"
console.log(object.property) //=> "value"
If the api is returning json inside an string, you could parse it and just go throught the elements till you find what you need. Otherwise how would you traverse the string? From my point of view, that's something you shouldn't do.
I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.
I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.