最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

LinQ foreach in javascriptjquery - Stack Overflow

programmeradmin1浏览0评论

How can I easily do these type of loops in Jquery or Javascript? Preferably without any other plugins.

string a = "";
foreach (var i in (from a in DbList1 select a.FieldA).Distinct())
{
   a += i + ", ";
}

and this

foreach (var i in DbList2)
{
   a += i.FieldB + ", ";
}

Loop number 2 could be solved like this atleast.

$.each(aData.DbList2, function (index, value) {
 a += value.FieldB;
);

Not 100% sure this is the most effective though

How can I easily do these type of loops in Jquery or Javascript? Preferably without any other plugins.

string a = "";
foreach (var i in (from a in DbList1 select a.FieldA).Distinct())
{
   a += i + ", ";
}

and this

foreach (var i in DbList2)
{
   a += i.FieldB + ", ";
}

Loop number 2 could be solved like this atleast.

$.each(aData.DbList2, function (index, value) {
 a += value.FieldB;
);

Not 100% sure this is the most effective though

Share Improve this question edited Jul 24, 2015 at 5:36 Jeff Mercado 135k33 gold badges266 silver badges280 bronze badges asked Jul 10, 2015 at 11:35 stigstig 1,2406 gold badges26 silver badges45 bronze badges 4
  • 2 are you iterating upon an array and getting something from each element ? Better to post a sample question like How to concatinate words in array ? Syntax from other languages are just confusing. – Mritunjay Commented Jul 10, 2015 at 11:36
  • In the javascript, its an array inside a object – stig Commented Jul 10, 2015 at 11:37
  • hi please find this URL that may be help to you stackoverflow./questions/11887450/… – Neo Vijay Commented Jul 10, 2015 at 11:43
  • a sample of your source data would go a long way to getting help on how to do something with it - I take it, since you don't want any libraries (except the biggest piece of bloat in existence, jQueery) linqjs.codeplex. is out of the question – Jaromanda X Commented Jul 10, 2015 at 11:44
Add a ment  | 

2 Answers 2

Reset to default 3

You can use map method for iterating array variable.

Code snippets:

var arr = jQuery.map( aData.DbList2, function(value) {
return value.FieldB;
});
//To get unique array variable
var uniqueArr = [];
$.each(arr, function (i, el) {
            if ($.inArray(el, uniqueArr) === -1) uniqueArr.push(el);
        });

Second one is easy enough to do in vanilla JavaScript:

var a = "";
for (var i = 0; i < DbList2.length; i++){
    a += DbList2[i].FieldB + ", ";
}

First one is a little trickier, but not impossible and can also be done with vanilla JS.

var a = "";
var uniques = [];

for (var i = 0; i < DbList1.length; i++ ){
    var fieldA = DbList1[i].FieldA;
    // check if we've already seen this value
    if (uniques.indexOf(fieldA) < 0)
    {
        // Nope, record it for future use
        uniques.push(fieldA)

        // and update the string.
        a += fieldA + ", ";
    }
}
发布评论

评论列表(0)

  1. 暂无评论