Is there something like Java's reflection where I can know what attributes are available?
for(var key in myObject) {
//do something with key
}
that enumerates through all properties
all properties for the window object http://jsfiddle.net/KdyLG/
This is one function that I use. You can specify which level of the array you which to dump.
alert(dump(myArray));
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
A way to do it:
for(var attrib in myObject){
if(typeof attrib != 'function') {
alert('this is attribute ' + attrib + 'with value' + myObject[attrib]);
} }
Related
{
field_country: ["England", "Netherlands", "India", "Italy"],
field_continent: ["Europe"],
field_group: ["Building", "People", "Landscape"
}
I want to loop over each item and return the key and the array together with ending 'OR' for example:
field_country: "England" OR field_country: "Netherlands"
The last item should not end with 'OR' in the loop. I am not sure what the best process is for this using vanilla JS. So far my code is as follows:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i == 1) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
I would be very grateful for any assistance.
Thanks in advance.
You can do something like this with Object.entries and Array.reduce if you would like to get the final result in the form of an object:
const data = { field_country: ["England", "Netherlands", "India", "Italy"], field_continent: ["Europe"], field_group: ["Building", "People", "Landscape"] }
const result = Object.entries(data).reduce((r, [k, v]) => {
r[k] = v.join(' OR ')
return r
}, {})
console.log(result)
It is somewhat unclear what is the final format you need to result in but that should help you to get the idea. If ES6 is not an option you can convert this to:
const result = Object.entries(data).reduce(function(r, [k, v]) {
r[k] = v.join(' OR ')
return r
}, {})
So there are is no arrow function etc.
The idea is to get the arrays into the arrays of strings and use the Array.join to do the "replacement" for you via join(' OR ')
Here's the idea. In your code you are appending " or " at the end of your strings starting at index 0. I suggest you append it at the the beginning starting at index 1.
var somewords = ["ORANGE", "GREEN", "BLUE", "WHITE" ];
var retval = somewords[0];
for(var i = 1; i< somewords.length; i++)
{
retval += " or " + somewords[i];
}
console.log(retval);
//result is: ORANGE or GREEN or BLUE or WHITE
Your conditional expression if (i == 1) would only trigger on the second iteration of the loop since i will only equal 1 one time.
Try something like:
if (i < (facetResults.length - 1)) {
// only add OR if this isn't the last element of the array
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
}
Here's your updated code:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i < (facetResults.length - 1)) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I've tried using the techniques mentioned in these questions, but I haven't had any luck. I'm trying to adjust a JavaScript function to retrieve multiple divs using the getElementById method.
Here is the current line of code within the function which retrieves the div #cat1:
var elem = document.getElementById(cat1);
Moving forward, I need this function to also retrieve the div #cat2.
jQuery can be loaded if there's a better method to accomplish this using their library?
Here is the full function (reference Line 3):
function getCategories(initial) {
var i;
var elem = document.getElementById('cat1');
if (initial == 1) {
jsonGroups = "";
jsonGroups = '{ xml: [], "pin": [] ';
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
jsonGroups = jsonGroups + ', "' + elem.childNodes[i].attributes.getNamedItem("id").value + '": [] ';
}
}
jsonGroups = jsonGroups + "}";
markerGroups = eval('(' + jsonGroups + ')');
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
var elemID = elem.childNodes[i].attributes.getNamedItem("id").value;
if (elemID != "user") {
elem.childNodes[i].innerHTML = "<a onclick='" + 'toggleGroup("' + elemID + '")' + "'>" + elem.childNodes[i].innerHTML + "</a>";
} else {
elem.childNodes[i].innerHTML = '<form id="userPOIForm" action="#" onsubmit="userPOIFind(this.userPOI.value); return false"><input id="userPOITxt" size="20" name="userPOI" value="' + elem.childNodes[i].innerHTML + '" type="text"><input id="userPOIButton" value="Go" type="submit"> </form>';
}
if (hasClass(elem.childNodes[i], "hidden") !== null) {
elem.childNodes[i].setAttribute("caption", "hidden");
} else {
elem.childNodes[i].setAttribute("caption", "");
}
if (elem.childNodes[i].attributes.getNamedItem("caption").value != "hidden") {
classAdder = document.getElementById(elemID);
addClass(classAdder, "visibleLayer");
}
}
}
}
for (i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeName == "LI") {
var catType = elem.childNodes[i].attributes.getNamedItem("id").value;
result = doSearch(elem.childNodes[i].attributes.getNamedItem("title").value, elem.childNodes[i].attributes.getNamedItem("id").value);
}
}
}
If you are trying to select all elements with an id that starts with cat, you can do this in jQuery like this:
$("[id^=cat]")
jQuery: Attributes Starts With Selector
Just make categoriesList be another parameter, and call the function twice.
now when I put my own Object in alert function I see
[Object object]
that is pointless information. is there any way using reflection to get all fields and values of those fields?
JSON.stringify is often times builtin and can serialize most objects you pass to it.
That said, you should probably just use a debugger or console.log instead of alert-ing things.
Here is one of many. But better to use console.log() then alert
function objectToString(o){
var parse = function(_o){
var a = [], t;
for(var p in _o){
if(_o.hasOwnProperty(p)){
t = _o[p];
if(t && typeof t == "object"){
a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
}
else {
if(typeof t == "string"){
a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
}
else{
a[a.length] = [ p+ ": " + t.toString()];
}
}
}
}
return a;
}
return "{" + parse(o).join(", ") + "}";
}
sure, maybe something like
function alertObject(0){
var str = "";
for(i in o)
str += i + " " + o[i] + "\n";
alert(str);
}
Edit :: Note this is just a silly little example.
so I'm parsing through a JSON object like so
if(val.function1!==""){
$("#contentFunction").text(val.function1);
}
if(val.function2!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2);
}
if(val.function3!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2
+ "; " + val.function3);
}
I'm wondiering if there is a better way of checking if my json object property is empty instead of having tons of conditions... this gets really messy if for instance I have up to val.function10
Thanks for your help
var strs = [];
for (var i = 0; i < 10; i++) {
var value = val["function" + i];
value && strs.push(value);
}
$("#contentFunction").text(strs.join("; "));
Something like this?
var content = "";
for (var prop in val) {
if (!val.hasOwnProperty(prop)) continue;
if (val[prop] !== "") {
content += "; " + val[prop];
}
}
Or in node.js (or modern browsers):
var c = Object.keys(val).filter(function (k) {
return val[k] !== "";
}).map(function (k) {
return val[k];
}).join("; ");
A tool like underscorejs will help you enumerate functions and properties.