I have an object 'res' and it holds a field:
res.headers=new object();
im using this field as a map which holds key and value meaning:
res.headers['key']='value';
is there any way to get the content of this map by iterating it without knowing the key?
thank you!
for(var key in res.headers) {
if(res.headers.hasOwnProperty(key)) {
console.log(key + " -> " + res.headers[key]);
}
}
or with Object.keys():
for(var key in Object.keys(res.headers)) {
console.log(key + " -> " + res.headers[key]);
}
Easiest thing to do is use a javascript library, like underscore for example, then use someting like:
arr = _.values(res.headers)
arr[0] // value of first element
Related
I have a simple array that I'm having the hardest time trying to sort. I'm thinking maybe it's because of the time format, so I'm unsure how to reference it or how I could sort the time, in this array format, so that I can sort it later.
//function created to input values
function put(key, value, obj) {
obj[key] = value;
return obj
}
//loads the document from ajax call
function loadDoc() {
//ajax call
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = xhttp.responseText;
//input data from webpage into dom element
document.getElementById('next').innerHTML = data
var test = document.getElementsByClassName('gridRow')
//create dict
var new_dict = {}
for(a=0;a<test.length;a++){
if(test[a].children[2].innerText == 'Ready') {
test[a].style.display = 'none';
//drops into the dictionary
put(String(test[a].children[0].innerText).replace(/\n/ig, ''),
test[a].children[3].innerText, new_dict)
}
}
document.getElementById('next').innerHTML = ''
//looping through the dict
for(var index in new_dict) {
document.getElementById('next').innerHTML += ("<br>" + index + " : " +
new_dict[index] + "<br>");
}
the output is the same order the names appear.
Whatever is creating new_dict is creating it incorrectly. It's an array, but the code creating it is using it like a plain object. I'd fix that so that it's, for instance, an array of objects.
But with your current structure:
If you want to loop through its properties in order alphabetically by the property names, you can use Object.keys to get the keys and sort it, then loop through the result via map creating the output:
document.getElementById('next').innerHTML = Object.keys(new_dict)
.sort((a, b) => a.localeCompare(b)) // Sorts lexicographically (loosely, "alphabetically")
.map(key => escapeHTML(key + ": " + new_dict[key]))
.join("<br>"); // Joins them with <br> in-between
}
...where escapeHTML encodes & and <, since you're generating HTML. A quick and dirty version (which is good enough for the above) would be something like:
// ONLY good enough to handle text that isn't in attributes
function escapeHTML(str) {
return str.replace(/&/g, "&").replace(/</g, "<");
}
Based on the way your array seems to be populated, and going for the simplist solution: why don't you just normalize the time value such that you have appropriately pre-pended 0s?
" john doe": "00:19:57"
" Guy Faux ": "00:36:40"
" Charles Sheen ": "01:35:37"
This is a dictionary, not an array. It would be more accurate to refer to the names as "keys" and not "indexes". In particular, the dictionary you have here maps names onto times. Anyway, one thing you could do is make a new dictionary that maps the times onto a list of names (as multiple names might have the same time). Then sort that dictionary's keys.
Use the following fix time formats :
function put(key, value, obj) {
obj[key] = value.replace(/(\b\d\b)/g,'0$1');
return obj;
}
then use:
Object.keys(new_dict)
.sort((a, b) => a.localeCompare(b))
.forEach(p=>document.getElementById('next').innerHTML +="<br>" + p + " : " +
new_dict[p] + "<br>");
Hi there I have the following code:
function showsaveobj(){
let patient = creatobj();
let befaktoren = patient.addfaktoren();
console.log(befaktoren);
let show = document.getElementById("show");
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + (function() {for (let entry of befaktoren.entries()){return entry}})();
};
This last function is invoked when I press save inside the html document. It creates an object with a surname and a lastname and it has a method which creates a map out of the values the user has entered into the form. The form has 24 values corresponding to the 24h of the day. So the map is 24 entries long. I want to print these entries into the html document as you can see above. It works fine with the name and the surname but when I use the for..of loop to write the single entries It only prints out the first entry of the map.
When I add
for (let x of befaktoren.entries()){console.log(x);}
The console shows me 24 Arrays with the key and the value inside. When I do the same thing inside the string with innerHtml it only writes the first array of the map into the document.
I am doing something wrong here, but i cannot figure out what. After searching the web for several days now i hope someone here can help me.
Thanks in advance
I think you misunderstood the Map.entries() method. entries() does not return an iterable object that you can traverse with a for loop, but instead it returns an Iterator that contains all the entries which you can then retrieve with the next() method.
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
A Map itself is iterable so you can use your for loop on the map itself.
Despite that
your code:
someString + (function() {
for (let entry of befaktoren.entries()) {
return entry
}
})()
will always put the first element only into your string.
instead do something like this:
var befaktorenFormatter = function(input) {
let formattedString;
// directly iterate over the input iterable
for (let entry of input) {
formattedString += entry;
}
// don't return the current entry, return the fully formatted string instead
return formattedString;
}
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
Map has the convenience method forEach for iterating over its contents.
Also see: http://devdocs.io/javascript/global_objects/map/foreach .
Instead of using a for loop you could also do something like this:
let befaktoren = new Map([['foo', 'bar'], ['bar', 'foo']]);
let befaktorenFormatter = function(input) {
let formattedString;
input.forEach(function(value, key) {
formattedString += `${key}: ${value}<br>`;
});
return formattedString;
};
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
I hope that helped.
Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>
This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
console.log('type of data[0][i] = ' + typeof data[0][i]);
if (typeof data[0][i] === 'string') {
json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
console.log(i);
console.log(data[0][i])
} else {
//Get infro from inner array
}
}
json = json + '}]';
console.log(json);
Try JSON.stringify(data) to convert object to string instead of your function.
To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];
You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.
Hi all i am calling a javascript function on WebView in android. I am sending a JSON data which will pass value to html.
My JSON data is in following format i have checked using online tools it is valid.
{"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"}
I am using following code to display parsed result in html using jquery.
var jsonObject = JSON.stringify(vk);
document.write(jsonObject);
$.each($.parseJSON(jsonObject), function(k, v)
{
document.write("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
});
It is giving me output in following manner
Parameter Value
Results [object Object]
TestStatus Passed
Test Game Test
Please help how to read all results. Why it is reading object object.
Just use recursion. You need to be able to handle multidimensional objects. Also, I usually use jquery for DOM or AJAX only. For something like this, you might not need it.
Your Json
var vk = {"Results":{
"Number of Tests":"2",
"Latency(avg)":"17",
"Failure":"0%",
"Latitude":"12° 55' 35.5872'' N",
"Longitude":"77° 36' 4.16916'' E","Latency(max)":"18",
"Latency(min)":"17"
},
"TestStaus":"Passed",
"Test":"Game Test"};
Recursive function
function drawJSON(obj){
for(var key in obj){
if(typeof obj[key] === 'object'){
drawJSON(obj[key]);
continue;
}
document.write("<div><span>" + key + "</span><span>" + obj[key] + "</span> </div>");
}
}
drawJSON(vk);
DEMO
The Results is object so it is showing as [object object]. You can do this by:
function printEach(jsonObject) {
$.each(jsonObject, function(k, v)
{
if(typeof v === 'object') {
printEach(v);
} else {
console.log("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
}
});
}
var vk = {"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"};
var jsonObject = JSON.stringify(vk);
printEach($.parseJSON(jsonObject));
You can see the fiddle http://jsfiddle.net/58grs/1/
I wish to iterate over an object's properties and change them all to include "" around the value stored in them.
This object is passed to a REST call and the above format must be enforced. I prefer to handle the addition of "" in a central location, rather when assigning the actual values (the code is very complex and long).
I know that you can iterate through the object's properties easily:
$.each(queryOptions, function(obj){console.log(obj)})
However, can I somehow get reference to the actual property and set it from within the iteration?
Input:
queryOptions.value1 = 1234;
queryOptions.value2 = "testing";
queryOptions.value3 = 555;
Desired output:
queryOptions.value1 = "1234";
queryOptions.value2 = ""testing"";
queryOptions.value3 = "555";
Thanks
I agree with Pointy that this seems an odd requirement. But if it's really a requirement:
Using $.each:
$.each(queryOptions, function(key) {
queryOptions[key] = '"' + queryOptions[key] + '"';
});
Or just using JavaScript without any library stuff:
var key;
for (key in queryOptions) {
if (queryOptions.hasOwnProperty(key)) {
queryOptions[key] = '"' + queryOptions[key] + '"';
}
}