javascript - 当查找具有特定属性的对象时,是否有类似 LINQ 的替代方法可以替代 JavaScript 中的循环?

标签 javascript jquery loops sharepoint

目前我的代码如下所示:

    var arrayListEnum = list.getEnumerator();

    while (arrayListEnum.moveNext()) {

        var listItem = arrayListEnum.get_current();
        if (listItem.get_id() == id) { 

            //stuff(listItem);
            break;
        }
    }

也许我只是被 C# 宠坏了,但我不太喜欢它的外观。在 JavaScript 或 jQuery(我不想包含整个其他库)中,有没有办法让我做类似的事情:

var item = (from items in list.getEnumerator() 
            where items.get_id() == id
            select items);

//stuff(item); 

var item = list.getEnumerator().Where(item => item.get_id() == id);
//stuff(item);

提前致谢。

最佳答案

我猜你会得到list item collection从列表中,在这种情况下,如果您只对通过 id 获取列表项感兴趣,那么我建议使用 SP.List.getItemById Method ,例如:

var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
    function() {
       console.log(item.get_id());
   },
   function(sender,args){
       console.log(args.get_message());
   });

Note: from performance perspective the advantage here that there is no need to request list item collection and then filter item on the client side

下面提供了一些示例,演示如何按属性查找/过滤集合中的列表项

1) 使用getEnumerator方法

function findListItem(items,propertyName,propertyValue)
{
   var e = items.getEnumerator();
   while (e.moveNext()) {
      var listItem = e.get_current();
      if (listItem.get_item(propertyName) == propertyValue) { 
          return listItem        
      }
   }
   return null;
}

2)使用for语句

function findListItem(items,propertyName,propertyValue)
{
   for(var i = 0; i < items.get_count();i++) {
      var listItem = items.get_item(i);
      if (listItem.get_item(propertyName) == propertyValue) { 
          return listItem        
      }
   }
   return null;
}

3)使用filter() method :

//returns array(!)
function findListItem(items,propertyName,propertyValue)
{
    return items.get_data().filter(function(item){
       if (item.get_item(propertyName) == propertyValue) { 
          return item        
       }   
    });
}

关于javascript - 当查找具有特定属性的对象时,是否有类似 LINQ 的替代方法可以替代 JavaScript 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30264613/

相关文章:

javascript - jQuery 无法正确解析相对 URL

c# - 如何使用 Javascript 更改 ASP.NET Gridview 的 cssClass?

javascript - 有没有办法可以检查数据属性是否存在?

jquery - 如何让这个demo中的下划线效果继续使用CSS?

c# - C# 中的奇怪(循环/线程/字符串/lambda)行为

javascript - 视差 WordPress 主题标签仅在 Google Chrome 中不起作用

javascript - 单击按钮获取表格行的内容

jquery - 使用 1 个添加到购物车按钮将 2 个产品添加到购物车 Shopify

R:将循环转换为向量化执行以实现行之间的相关性

javascript - 数组数组转换为对象数组