Can someone tell me what wrong with my code? [closed] - javascript
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to
Create json object
Declare the products array in a json object
Create five json object in array
Each json object contains following keys
p_id
p_name
p_cost
However, I'm not getting the output result.
var data = {
"products": [{
"p_id": 111,
"p_name": "p_one",
"p_cost": 100
}];
};
var results = "";
for (var i = 0, i < data.products.length) {
var obj = data.products[i];
var _pid = obj.p_id;
var _pname = obj.p_name;
var _cost = obj.p_cost;
results = _pid + "." + _pname + "." + _pcost + "<br>";
}
console.log(results);
JavaScript 101, check your console for errors, there are a few:
extra ; inside json
undefined _pcost which should be _cost
unfinished/incorrect for loop: ; instead of , inside for loops in JavaScript, + the iteration counter missing
var data = {
"products": [{
"p_id": 111,
"p_name": "p_one",
"p_cost": 100
}]
};
var results = "";
for (var i = 0; i < data.products.length; i++) {
var obj = data.products[i];
var _pid = obj.p_id;
var _pname = obj.p_name;
var _cost = obj.p_cost;
results = _pid + "." + _pname + "." + _cost + "<br>";
}
console.log(results)
Related
How to remove identical query parameters from URL [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 1 year ago. Improve this question I need to remove duplicated query string parameters from the URL input example http://example.com/?foo=42&bar=43&foo=42&bar=43 need it to be Expected output: http://example.com/?foo=42&bar=43 I'm using this jquery code, but doesn't work function removeDuplicate(url) { url = decodeURIComponent(url); // decode the url,remove %5B becomes var query = url.split('?')[1]; // get only the query var parts = query.split('&'); // split the query into parts var params = {}; for (var i = 0; i < parts.length; i++) { var nv = parts[i].split('='); if (!nv[0]) continue; var value = nv[1] || true; if (params[nv[0]] && params[nv[0]].indexOf(value)) { params[nv[0]].push(value); } else { params[nv[0]] = [value]; } } url = url.split('?')[0] + '?'; var keys = Object.keys(params); for (var i = 0; i < keys.length; i++) { url += keys[i] + '=' + params[keys[i]].join('+'); if (i !== keys.length - 1) url += '&'; } return url; } removeDuplicate(window.location.href) Is that code correct or am I missing something? Thanks
One of the ways to make it done: const link = "http://example.com/?foo=42&bar=43&foo=42&bar=43" const params = link.replace(/.*\?/g, '') // replace everything before '?' .split('&') // split by '&' .filter((e, i, a) => a.indexOf(e) === i) // filter duplicates .join('&') // join by '&' const res = link.replace(/\?.*/g, '?' + params) // replace link params with params without duplicates console.log(res)
This should work: //var current = document.getElementById("current").innerHTML = //window.location.href; var current = 'http://example.com/?foo=42&bar=43&foo=42&bar=43'; console.log('current', current); var splitUrl = current.split('&'); console.log(splitUrl); var newUrl = splitUrl[0] + '&' + splitUrl[3] ; console.log(newUrl); Just uncomment the first two lines and comment the third line out. That's it.
insert a string at a specific position [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 6 years ago. Improve this question i have an array and i want to insert "ZZ" if the current array value(string) contains "ata", the code should replace at the end of "ata" word. var duplicatesArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak" ]; var uniqueArray = duplicatesArray.filter(function(elem, pos) { return duplicatesArray.indexOf(elem) == pos; }); for (var i = 0; i < uniqueArray.length; i++) { var st = uniqueArray[i]; if((st.endsWith("mak")==false) && (st.endsWith("mek")== false) && (st.length>3)) { var b = "ata"; var insert = "ZZ"; var position = st.indexOf("b"); st = st.slice(0, position) + insert + st.slice(position); document.writeln(st); document.write("<br>"); } }
I may need to edit this answer later once some details have been clarified, but it seems like you should use the .map() method on your uniqueArray. This code will walk through each word in the list and either let it unchanged or apply the replacement if all conditions are fulfilled. // using a shorter, already deduplicated list for sake of clarity var uniqueArray = [ "abıca","gelmek","ata","atabeg","at","eri","yir","atalar","tutmak" ]; var result = uniqueArray.map(function(word) { return ( !word.endsWith("mak") && !word.endsWith("mek") && word.length > 3 ? word.replace(/ata/, "ataZZ") : word ); }); console.log(result);
I am right or wrong? :) var initialArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"]; var newArray = [] var regexp = /(ata)(.*)?/; for (var i = 0; i< initialArray.length; i += 1) { newArray.push(initialArray[i].replace(regexp, "$1ZZ$2")) } console.log(newArray) // ... "gelmek", "ataZZ", "ataZZbeg" ...
how to create a json object in javascript for loop [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 7 years ago. Improve this question I would like to create a JSON object inside a for loop using javascript. I am expecting an result something like this: { "array":[ { "value1":"value", "value2":"value" }, { "value1":"value", "value2":"value" } ] } Can somebody help me on how to achieve this result in javascript ?
Instead of creating the JSON in the for-loop, create a regular JavaScript object using your for-loops and use JSON.stringify(myObject) to create the JSON. var myObject = {}; for(...) { myObject.property = 'newValue'; myObject.anotherProp = []; for(...) { myObject.anotherProp.push('somethingElse'); } } var json = JSON.stringify(myObject);
var loop = []; for(var x = 0; x < 10; x++){ loop.push({value1: "value_a_" + x , value2: "value_b_" + x}); } JSON.stringify({array: loop});
This code produces what you need: var result = {"array": []}; for(var i = 0; i < 2; i++){ var valueDict = {}; for(var j = 0; j < 2; j++){ valueDict["value" + (j+1).toString()] = "value"; } result["array"].push(valueDict); } It uses the push function to add items to the list, and the indexer [] notation notation to modify the entries on the object prototype. Hope it helps,
Improving performance while iterating two nested loops [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. This question does not appear to be about programming within the scope defined in the help center. Closed 7 years ago. Improve this question I calculate a "Top-5-List" of Birthplaces organized in an array of objects in this form var myObjArr =[ { "birth": { "year": 2012, "name": "Manchester, Vermont, USA", } } , (and so on) ]; My approach however does not seem to be much performant: for (var i = 0; i < myObjArr.length; i++) { var alreadyListed = -1; for (var j = 0; j < resultData.length; j++) { if(resultData[j].key == myObjArr[i]['birth']['name']) { // birthname already in resultData alreadyListed = j; break; } } if(alreadyListed != -1 ) { // birthname already in resultData -> raise count resultData[alreadyListed].count += 1; }else { // birthname not yet in resultData -> add to resultData resultData.push({key: myObjArr[i]['birth']['name'], count: 1 }); } } } Neiter javascript's forEach nor angulars angular.forEach seem to improve the performance. Any Suggestions?
You can use an object as a dictionary instead of using an array and looking for a key by iterating, this way the second "loop" is done by the Javascript implementation when looking for object keys (also it's probably not a linear scan but an hash table lookup): var result = {}; myObjArr.forEach(function(obj) { var key = "!" + obj.birth.name; result[key] = 1 + (result[key] || 0); }); I'm always adding a "!" in front of the key when using objects as dictionaries because all Javascript objects do have an inherited constructor property and I don't want to interfer with that. The (x || 0) trick is to start with a 0 when a name has not seen before (undefined is falsy in Javascript). Adding 1 to undefined instead results in NaN. If you really need an array as result the code is only slightly more complex: var result = []; var index = {}; myObjArr.forEach(function(obj) { var key = "!" + obj.birth.name; var ix = index[key]; if (ix === undefined) { // Allocate a new entry index[key] = result.length; result.push({key:key, count:1}); } else { result[ix].count += 1; } });
cut the string in javascript [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. This question does not appear to be about programming within the scope defined in the help center. Closed 8 years ago. Improve this question cut the string from last '/' to '.html' I have a string like that "/Views/GS/stockView.html" My need the name "stockView" How can I cut the name from a string? Thanks.
a = "/Views/GS/stockView.html"; a.split('/').pop().split(".")[0]; Demo
use indexOf() and lastIndexOf() method, like var str = "/Views/GS/stockView.html"; var slashPos = str.lastIndexOf('/'); var dotPos = str.indexOf('.', slashPos + 1); var result = str.substring(slashPos + 1, dotPos);
Try using RegExp: var view = function(str) { return str.match(/\/(\w*)\./)[1];//finds a word between `/` and `.` }; console.log(view("/Views/GS/stockView.html")); console.log(view("/Views/fs/inventView.html")); console.log(view("/Views/fs/p1/showView.jsp")); console.log(view("/Views/fs/p2/showView123.aspx")); Open console
Try this var msg = "/Views/GS/stockView.html"; var startIndex = -1; var endIndex=-1; var length = msg.length; for (var i = length - 1; i >= 0; i--) { if (msg[i] == '/'){ startIndex=i+1; break; } if(msg[i]==".") endIndex=i; } console.log(msg.substr(startIndex,endIndex-startIndex)); Or try this var msg = "/Views/GS/stockView.html"; var split=msg.split("/"); split=split[split.length-1].split("."); console.log(split[0]);