Looping data in javascript - javascript

How can I get the value BrandName in this image using javascript loop.

UPDATED: Since data variable you use to display the response is already a CartObject then use:
for (var i = 0, len = data.CartLists.length; i < len; i++) {
console.log( data.CartLists[i].Item.BrandName );
}

An alternative to the one VisioN said is the following:
for (var CartItemId in CartObject.CartLists) {
Console.log(CartObject.CartLists[CartItemId].Item.BrandName);
}
However, If you would attach an Prototype to the JSON object, you could obtain an Object in the for-loop instead of an Integer (Number).
for (var CartItem in CartObject.CarLists) {
Console.log(CartItem.Item.BrandName);
}
Note that if you are going to make everything right, you should insert the following in the for-loop:
if (CartObject.CarLists.hasOwnProperty(CartItem)) {
Console.log(CartItem.Item.BrandName);
}
This example will work, but as seen in the comments below. The use of it is not what it is designed for. The For-In loop is designed to loop over Object properties, not Array items.

Related

NodeJS Call GET method within for loop using callbacks

I am using NodeJS and Express and iterating over an array of strings, for example:
[ "1" , "+" , "B4", "*", "8"]
If the string contains a letter, the function should go off and call a GET method to retrieve a value from the Database. My code so far looks like this:
function processFormula(formula) {
console.log(formula)
var arr = formula.split(" ");
for (var i = 0; i < arr.length; i++) {
if (arr[i].match(/[a-z]/i)) {
/* fetch the value and store it in arr[i] */
}
return arr.toString();
}
My problem is that the method which goes off to fetch the value takes longer to execute than the processing thread, resulting in
undefined
cropping up a lot. I am struggling to understand where exactly I should be placing my callback to deal with this situation iteratively?
Any help is greatly appreciated!
That is tricky to coordinate. You could try using a HTTP request library like axios that uses promises. Then, you can use Promise.all to coordinate all the requests.
You can add another if inside the for and return until you at the last element:
for(var i = 0; i < arr.length; i++){
if (arr[i].match(/[a-z]/i)) {
/* fetch the value and store it in arr[i] */
}
if(i == arr.length-1){
return arr.toString();
}
}
And a suggestion, try using array.length outside for loops, because each loop you will be calculating the length of the array to check if condition is achieved, therefore going through array each time. (I didn't change that in my answer). Just do it before the loop and do var size = array.length

Simple for loop with JsRender

I'm using JsRender to render a template client-side. However, I'm unable to use the for loop tag to repeat an html-portion of the block because it seems to accept only arrays or objects. Instead, my JSON return a variable which is a number (the number of times I should repeat the block). How can I repeat html N times using JsRender?
I extended #webdeveloper answer, as there is no need for additional loop because javascript arrays are working in a way that you only have to define last element
$.views.helpers({
repeatLoop: function( count ) {
if (!count) return [];
var repeat = [];
repeat[count-1] = {};
return repeat;
}
});
And then use as
#{{for ~repeatLoop(10)}}
{{:#index+1}}
#{{/for}}
I am not sure, that JsRender provide this functionality from the box. You can write your own tag, like here: Example Scenario: Creating custom helpers to iterate through fields
$.views.helpers({
getFields: function( count ) {
var fieldsArray = [];
for (var i=0; i < count; i++) {
fieldsArray.push({});
}
return fieldsArray;
}
});
Demo: http://jsfiddle.net/6UeZC/

Javascript or Jquery - for each on this array

See a screenshot of my returned data i did a console.log on which i need to do a for each on.
i have been trying things like this to no avail...?
for (var point in arrayLatLngPoints)
{
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}
Don't use for..in to loop an array, use normal for loop instead.
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}

Can I select 2nd element of a 2 dimensional array by value of the first element in Javascript?

I have a JSON response like this:
var errorLog = "[[\"comp\",\"Please add company name!\"],
[\"zip\",\"Please add zip code!\"],
...
Which I'm deserializing like this:
var log = jQuery.parseJSON(errorLog);
Now I can access elements like this:
log[1][1] > "Please add company name"
Question:
If I have the first value comp, is there a way to directly get the 2nd value by doing:
log[comp][1]
without looping through the whole array.
Thanks for help!
No. Unless the 'value' of the first array (maybe I should say, the first dimension, or the first row), is also it's key. That is, unless it is something like this:
log = {
'comp': 'Please add a company name'
.
.
.
}
Now, log['comp'] or log.comp is legal.
There are two was to do this, but neither avoids a loop. The first is to loop through the array each time you access the items:
var val = '';
for (var i = 0; i < errorLog.length; i++) {
if (errorLog[i][0] === "comp") {
val = errorLog[i][1];
break;
}
}
The other would be to work your array into an object and access it with object notation.
var errors = {};
for (var i = 0; i < errorLog.length; i++) {
errors[errorLog[i][0]] = errorLog[i][1];
}
You could then access the relevant value with errors.comp.
If you're only looking once, the first option is probably better. If you may look more than once, it's probably best to use the second system since (a) you only need to do the loop once, which is more efficient, (b) you don't repeat yourself with the looping code, (c) it's immediately obvious what you're trying to do.
No matter what you are going to loop through the array somehow even it is obscured for you a bit by tools like jQuery.
You could create an object from the array as has been suggested like this:
var objLookup = function(arr, search) {
var o = {}, i, l, first, second;
for (i=0, l=arr.length; i<l; i++) {
first = arr[i][0]; // These variables are for convenience and readability.
second = arr[i][1]; // The function could be rewritten without them.
o[first] = second;
}
return o[search];
}
But the faster solution would be to just loop through the array and return the value as soon as it is found:
var indexLookup = function(arr, search){
var index = -1, i, l;
for (i = 0, l = arr.length; i<l; i++) {
if (arr[i][0] === search) return arr[i][1];
}
return undefined;
}
You could then just use these functions like this in your code so that you don't have to have the looping in the middle of all your code:
var log = [
["comp","Please add company name!"],
["zip","Please add zip code!"]
];
objLookup(log, "zip"); // Please add zip code!
indexLookup(log, "comp"); // Please add company name!
Here is a jsfiddle that shows these in use.
Have you looked at jQuery's grep or inArray method?
See this discussion
Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

Can I loop through 2 objects at the same time in JavaScript?

related (sort of) to this question. I have written a script that will loop through an object to search for a certain string in the referring URL. The object is as follows:
var searchProviders = {
"google": "google.com",
"bing": "bing.com",
"msn": "search.msn",
"yahoo": "yahoo.co",
"mywebsearch": "mywebsearch.com",
"aol": "search.aol.co",
"baidu": "baidu.co",
"yandex": "yandex.com"
};
The for..in loop I have used to loop through this is:
for (var mc_u20 in mc_searchProviders && mc_socialNetworks) {
if(!mc_searchProviders.hasOwnProperty(mc_u20)) {continue;}
var mc_URL = mc_searchProviders[mc_u20];
if (mc_refURL.search(mc_URL) != -1) {
mc_trackerReport(mc_u20);
return false;
}
Now I have another object let's call it socialNetworks which has the following construct:
var socialNetworks = {"facebook" : "facebook.co" }
My question is, can I loop through both of these objects using just one function? the reason I ask is the variable mc_u20 you can see is passed back to the mc_trackerReport function and what I need is for the mc_u20 to either pass back a value from the searchProviders object or from the socialNetworks object. Is there a way that I can do this?
EDIT: Apologies as this wasn't explained properly. What I am trying to do is, search the referring URL for a string contained within either of the 2 objects. So for example I'm doing something like:
var mc_refURL = document.referrer +'';
And then searching mc_refURL for one of the keys in the object, e.g. "google.com", "bing.com" etc. 9this currently works (for just one object). The resulting key is then passed to another function. What I need to do is search through the second object too and return that value. Am I just overcomplicating things?
If I understand your question correctly, you have a variable mc_refURL which contains some URL. You want to search through both searchProviders and socialNetworks to see if that URL exists as a value in either object, and if it does you want to call the mc_trackerReport() function with the property name that goes with that URL.
E.g., for mc_refURL === "yahoo.co" you want to call mc_trackerReport("yahoo"), and for mc_ref_URL === "facebook.co" you want to call mc_trackerReport("facebook").
You don't say what to do if the same URL appears in both objects, so I'll assume you want to use whichever is found first.
I wouldn't create a single merged object with all the properties, because that would lose information if the same property name appeared in both original objects with a different URL in each object such as in an example like a searchProvider item "google" : "google.co" and a socialNetworks item "google" : "plus.google.com".
Instead I'd suggest making an array that contains both objects. Loop through that array and at each iteration run your original loop. Something like this:
var urlLists = [
mc_searchProviders,
mc_socialNetworks
],
i,
mc_u20;
for (i = 0; i < urlLists.length; i++) {
for (mc_u20 in urlLists[i]) {
if(!urlLists[i].hasOwnProperty(mc_u20))
continue;
if (mc_refURL.search(urlLists[i][mc_u20]) != -1) {
mc_trackerReport(mc_u20);
return false;
}
}
}
The array of objects approach is efficient, with no copying properties around or anything, and also if you later add another list of URLs, say programmingForums or something you simply add that to the end of the array.
You could combine the two objects into one before your loop. There's several approaches here:
How can I merge properties of two JavaScript objects dynamically?
var everything = searchProviders;
for (var attrname in socialNetworks) { everything[attrname] = socialNetworks[attrname]; }
for(var mc_u20 in everything) {
// ...
}
for (var i = 0; i < mc_searchProviders.length; i++) {
var searchProvider = mc_searchProviders[i];
var socialNetwork = mc_socialNetworks[i];
if (socialNetwork != undefined) {
// Code.
}
}
Or am i horribly misunderstanding something?

Categories