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!!!
Related
The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
{
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;
}
});
I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}
I need to loop all the json object and frame into html. I can iterate all the json object but I could not get only one json object(first json object).
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
console.log('response length:' + obj.length);
for (var i = 0; i < obj.length; i++) {
var finalResult = "";
var objects = obj[i];
for (var key in objects) {
var res = "<tr><td>" + objects.ID + "</td><td>" + objects.mobile + "</td><td>" + objects.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult = res.concat(res);
console.log('finalResult:' + finalResult);
}
}
And i am unable to put everything into 'tr' element since javascript doest not have stringbuffer. I think it can be by using StringBuffer in java. How can it be done using javascript/jquery?
Pls help me.
The issue is because you're redefining the variable you're looping over, obj, within the iterating function.
As you've tagged this using jQuery, so here's a shorter alternative using $.each to build the table:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
var phones = JSON.parse(res);
$.each(phones, function(i, obj) {
$('<tr />')
.append('<td>' + obj.ID + '</td><td>' + obj.mobile + '</td><td>' + obj.feedback + '</td><td>')
.appendTo('table');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
You don't need the inner for loop, you can access your elements directly. I made a couple of other changes as well that can be found below:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
var finalResult = "";
console.log('response length:' + obj.length);
for (var i = 0; i < obj.length; i++) {
var str1 = "aasd";
var tableRow = "<tr><td>" + obj[i]["ID"] + "</td><td>" + obj[i]["mobile"] + "</td><td>" + obj[i]["feedback"] + "</td><td></tr>";
finalResult += tableRow;
}
console.log('finalResult:' + finalResult);
I hope you find it helpful.
You are redefining obj in the middle of your code:
var obj = obj[i];
Use another name:
You are also resetting your finalResult inside the loop (and the inner loop is not required):
http://jsfiddle.net/7j52myca/
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
var phones = JSON.parse(res);
console.log('response length:' + phones.length);
var finalResult = "";
for (var i = 0; i < phones.length; i++) {
var str1 = "aasd";
var obj = phones[i];
var res = "<tr><td>" + obj.ID + "</td><td>" + obj.mobile + "</td><td>" + obj.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult += res;
}
console.log('finalResult:' + finalResult);
$('#result').append(finalResult);
You can do the same thing a lot shorter using pure jQuery, but #Rory McCrossan has already posted a good version like that so I will not bother adding one here.
I think you want to do this:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
console.log('response length:' + obj.length);
var finalResult = "";
for (var i = 0; i < obj.length; i++) {
var str1 = "aasd";
var obj1 = obj[i];
for (var key in obj1) {
var res = "<tr><td>" + obj1.ID + "</td><td>" + obj1.mobile + "</td><td>" + obj1.feedback + "</td><td></tr>";
//console.log('res:' + res);
finalResult += res;
}
}
console.log('finalResult:' + finalResult);
use jquery each method you can do it
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
var finalResult = "";
$.each(obj, function(i, item) {
var res = "<tr><td>" + item.ID + "</td><td>" + item.mobile + "</td><td>" + item.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult += res;
});
$('body').append(finalResult)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
see this code
var jsonobj = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(jsonobj);
alert(obj);
$.each(obj, function (index, item) {
$('<tr/>')
.append('<td>' + item.ID + '</td><td>' + item.mobile + '</td><td>' + item.feedback + '</td><td>')
.appendTo('table');
});
fiddle:http://jsfiddle.net/21wrqrfb/
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}