记录一下,方便自己查找。。。

自己在开发前端时,对于处理JSON,觉得真是枯燥。处理数据,基本都要循环。 所以我想着前端也能跟后端一样,有Linq来处理我的JSON对象就好了。上网一搜,找到了JSLINQ.js。。实现了自己的需求,嘿嘿嘿。

首先是JSLINQ.js 代码。 下载地址

自己贴一下:

  1. //-----------------------------------------------------------------------
  2. // Part of the LINQ to JavaScript (JSLINQ) v2.20 Project - http://jslinq.codeplex.com
  3. // Copyright (C) 2012 Chris Pietschmann (http://pietschsoft.com). All rights reserved.
  4. // This license can be found here: http://jslinq.codeplex.com/license
  5. //-----------------------------------------------------------------------
  6. (function () {
  7. var JSLINQ = window.jslinq = window.JSLINQ = function (dataItems) {
  8. return new JSLINQ.fn.init(dataItems);
  9. },
  10. utils = {
  11. processLambda: function (clause) {
  12. // This piece of "handling" C#-style Lambda expression was borrowed from:
  13. // linq.js - LINQ for JavaScript Library - http://lingjs.codeplex.com
  14. // THANK!!
  15. if (utils.isLambda(clause)) {
  16. var expr = clause.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/);
  17. return new Function(expr[1], "return (" + expr[2] + ")");
  18. }
  19. return clause;
  20. },
  21. isLambda: function (clause) {
  22. return (clause.indexOf("=>") > -1);
  23. },
  24. randomIndex: function (max, existing) {
  25. var q, r, f = function () { return this == r; };
  26. if (!existing) {
  27. return parseInt(Math.random() * max, 10);
  28. } else {
  29. q = JSLINQ(existing);
  30. r = -1;
  31. while (r < 0 || q.Where(f).Count() !== 0) {
  32. r = utils.randomIndex(max);
  33. }
  34. return r;
  35. }
  36. }
  37. };
  38. JSLINQ.fn = JSLINQ.prototype = {
  39. init: function (dataItems) {
  40. this.items = dataItems;
  41. },
  42.  
  43. // The current version of JSLINQ being used
  44. jslinq: "2.20",
  45.  
  46. toArray: function () { return this.items; },
  47. where: function (clause) {
  48. var newArray = [], len = this.items.length;
  49.  
  50. // The clause was passed in as a Method that return a Boolean
  51. for (var i = 0; i < len; i++) {
  52. if (clause.apply(this.items[i], [this.items[i], i])) {
  53. newArray[newArray.length] = this.items[i];
  54. }
  55. }
  56. return JSLINQ(newArray);
  57. },
  58. select: function (clause) {
  59. var item, newArray = [], field = clause;
  60. if (typeof (clause) !== "function") {
  61. if (clause.indexOf(",") === -1) {
  62. clause = function () { return this[field]; };
  63. } else {
  64. clause = function () {
  65. var i, fields = field.split(","), obj = {};
  66. for (i = 0; i < fields.length; i++) {
  67. obj[fields[i]] = this[fields[i]];
  68. }
  69. return obj;
  70. };
  71. }
  72. }
  73.  
  74. // The clause was passed in as a Method that returns a Value
  75. for (var i = 0; i < this.items.length; i++) {
  76. item = clause.apply(this.items[i], [this.items[i]]);
  77. if (item) {
  78. newArray[newArray.length] = item;
  79. }
  80. }
  81. return JSLINQ(newArray);
  82. },
  83. orderBy: function (clause) {
  84. var tempArray = [];
  85. for (var i = 0; i < this.items.length; i++) {
  86. tempArray[tempArray.length] = this.items[i];
  87. }
  88.  
  89. if (typeof (clause) !== "function") {
  90. var field = clause;
  91. if (utils.isLambda(field)) {
  92. clause = utils.processLambda(field);
  93. }
  94. else {
  95. clause = function () { return this[field]; };
  96. }
  97. }
  98.  
  99. return JSLINQ(
  100. tempArray.sort(function (a, b) {
  101. var x = clause.apply(a, [a]), y = clause.apply(b, [b]);
  102. return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  103. })
  104. );
  105. },
  106. orderByDescending: function (clause) {
  107. var tempArray = [], field;
  108. for (var i = 0; i < this.items.length; i++) {
  109. tempArray[tempArray.length] = this.items[i];
  110. }
  111.  
  112. if (typeof (clause) !== "function") {
  113. field = clause;
  114. if (utils.isLambda(field)) {
  115. clause = utils.processLambda(field);
  116. }
  117. else {
  118. clause = function () { return this[field]; };
  119. }
  120. }
  121.  
  122. return JSLINQ(tempArray.sort(function (a, b) {
  123. var x = clause.apply(b, [b]), y = clause.apply(a, [a]);
  124. return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  125. }));
  126. },
  127. selectMany: function (clause) {
  128. var r = [];
  129. for (var i = 0; i < this.items.length; i++) {
  130. r = r.concat(clause.apply(this.items[i], [this.items[i]]));
  131. }
  132. return JSLINQ(r);
  133. },
  134. count: function (clause) {
  135. if (clause === undefined) {
  136. return this.items.length;
  137. } else {
  138. return this.Where(clause).items.length;
  139. }
  140. },
  141. distinct: function (clause) {
  142. var item, dict = {}, retVal = [];
  143. for (var i = 0; i < this.items.length; i++) {
  144. item = clause.apply(this.items[i], [this.items[i]]);
  145. // TODO - This doesn't correctly compare Objects. Need to fix this
  146. if (dict[item] === undefined) {
  147. dict[item] = true;
  148. retVal.push(item);
  149. }
  150. }
  151. dict = null;
  152. return JSLINQ(retVal);
  153. },
  154. any: function (clause) {
  155. for (var i = 0; i < this.items.length; i++) {
  156. if (clause.apply(this.items[i], [this.items[i], i])) { return true; }
  157. }
  158. return false;
  159. },
  160. all: function (clause) {
  161. for (var i = 0; i < this.items.length; i++) {
  162. if (!clause(this.items[i], i)) { return false; }
  163. }
  164. return true;
  165. },
  166. reverse: function () {
  167. var retVal = [];
  168. for (var i = this.items.length - 1; i > -1; i--) {
  169. retVal[retVal.length] = this.items[i];
  170. }
  171. return JSLINQ(retVal);
  172. },
  173. first: function (clause) {
  174. if (clause !== undefined) {
  175. return this.Where(clause).First();
  176. }
  177. else {
  178. // If no clause was specified, then return the First element in the Array
  179. if (this.items.length > 0) {
  180. return this.items[0];
  181. } else {
  182. return null;
  183. }
  184. }
  185. },
  186. last: function (clause) {
  187. if (clause !== undefined) {
  188. return this.Where(clause).Last();
  189. }
  190. else {
  191. // If no clause was specified, then return the First element in the Array
  192. if (this.items.length > 0) {
  193. return this.items[this.items.length - 1];
  194. } else {
  195. return null;
  196. }
  197. }
  198. },
  199. elementAt: function (i) {
  200. return this.items[i];
  201. },
  202. concat: function (array) {
  203. var arr = array.items || array;
  204. return JSLINQ(this.items.concat(arr));
  205. },
  206. intersect: function (secondArray, clause) {
  207. var clauseMethod, sa = (secondArray.items || secondArray), result = [];
  208. if (clause !== undefined) {
  209. clauseMethod = clause;
  210. } else {
  211. clauseMethod = function (item, index, item2, index2) { return item === item2; };
  212. }
  213.  
  214. for (var a = 0; a < this.items.length; a++) {
  215. for (var b = 0; b < sa.length; b++) {
  216. if (clauseMethod(this.items[a], a, sa[b], b)) {
  217. result[result.length] = this.items[a];
  218. }
  219. }
  220. }
  221. return JSLINQ(result);
  222. },
  223. defaultIfEmpty: function (defaultValue) {
  224. if (this.items.length === 0) {
  225. return defaultValue;
  226. }
  227. return this;
  228. },
  229. elementAtOrDefault: function (i, defaultValue) {
  230. if (i >= 0 && i < this.items.length) {
  231. return this.items[i];
  232. }
  233. return defaultValue;
  234. },
  235. firstOrDefault: function (defaultValue) {
  236. return this.First() || defaultValue;
  237. },
  238. lastOrDefault: function (defaultValue) {
  239. return this.Last() || defaultValue;
  240. },
  241. take: function (count) {
  242. return this.Where(function (item, index) { return index < count; });
  243. },
  244. skip: function (count) {
  245. return this.Where(function (item, index) { return index >= count; });
  246. },
  247. each: function (clause) {
  248. var len = this.items.length;
  249. for (var i = 0; i < len; i++) {
  250. clause.apply(this.items[i], [this.items[i], i]);
  251. }
  252. return this;
  253. },
  254. random: function (count) {
  255. var len = this.Count(), rnd = [];
  256. if (!count) { count = 1; }
  257. for (var i = 0; i < count; i++) {
  258. rnd.push(utils.randomIndex(len - 1, rnd));
  259. }
  260. rnd = JSLINQ(rnd);
  261. return this.Where(function (item, index) {
  262. return rnd.Where(function () {
  263. return this == index;
  264. }).Count() > 0;
  265. });
  266. }
  267. };
  268.  
  269. (function (fn) {
  270. fn.ToArray = fn.toArray;
  271. fn.Where = fn.where;
  272. fn.Select = fn.select;
  273. fn.OrderBy = fn.orderBy;
  274. fn.OrderByDescending = fn.orderByDescending;
  275. fn.SelectMany = fn.selectMany;
  276. fn.Count = fn.count;
  277. fn.Distinct = fn.distinct;
  278. fn.Any = fn.any;
  279. fn.All = fn.all;
  280. fn.Reverse = fn.reverse;
  281. fn.First = fn.first;
  282. fn.Last = fn.last;
  283. fn.ElementAt = fn.elementAt;
  284. fn.Concat = fn.concat;
  285. fn.Intersect = fn.intersect;
  286. fn.DefaultIfEmpty = fn.defaultIfEmpty;
  287. fn.ElementAtOrDefault = fn.elementAtOrDefault;
  288. fn.FirstOrDefault = fn.firstOrDefault;
  289. fn.LastOrDefault = fn.lastOrDefault;
  290. fn.Take = fn.take;
  291. fn.Skip = fn.skip;
  292. fn.Each = fn.each;
  293. fn.Random = fn.random;
  294. })(JSLINQ.fn);
  295.  
  296. JSLINQ.fn.init.prototype = JSLINQ.fn;
  297. })();

使用方式:

页面代码

  1. <!DOCTYPE html>
  2.  
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width" />
  6. <title>LinqToJS</title>
  7. <script src="~/Scripts/JSLINQ.js"></script>
  8. <script src="~/Scripts/jquery-1.6.2.min.js"></script>
  9. </head>
  10. <body>
  11. <div>
  12. <h3>linq to js</h3>
  13. </div>
  14. </body>
  15. </html>
  16. <script type="text/javascript">
  17. $(function() {
  18. var str = "{\"zhang\":[{\"name\":\"张大佛爷\",\"Age\":\"170\",\"sex\":\"男\"},{\"name\":\"张启灵\",\"Age\":\"100\",\"sex\":\"男\"}],\"wu\":[{\"name\":\"吴邪\",\"Age\":\"25\",\"sex\":\"男\"}]}";
  19. var list = JSON.parse(str);
  20.  
  21. var sample1 = JSLINQ(list.zhang).Where(function () { return this.name == '张大佛爷'; });
  22.  
  23. var sample2 = JSLINQ(list.zhang).Select(function () { return this.name; });
  24.  
  25. return sample1;
  26.  
  27. })
  28. </script>

效果:就跟LINQ一样,没啥好说的,看一下方法格式就行

sample1 sample2

LIINQ TO JS的更多相关文章

  1. Vue.js 和 MVVM 小细节

    MVVM 是Model-View-ViewModel 的缩写,它是一种基于前端开发的架构模式,其核心是提供对View 和 ViewModel 的双向数据绑定,这使得ViewModel 的状态改变可以自 ...

  2. js学习笔记:操作iframe

    iframe可以说是比较老得话题了,而且网上也基本上在说少用iframe,其原因大致为:堵塞页面加载.安全问题.兼容性问题.搜索引擎抓取不到等等,不过相对于这些缺点,iframe的优点更牛,跨域请求. ...

  3. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  4. JS调用Android、Ios原生控件

    在上一篇博客中已经和大家聊了,关于JS与Android.Ios原生控件之间相互通信的详细代码实现,今天我们一起聊一下JS调用Android.Ios通信的相同点和不同点,以便帮助我们在进行混合式开发时, ...

  5. jquery和Js的区别和基础操作

    jqery的语法和js的语法一样,算是把js升级了一下,这两种语法可以一起使用,只不过是用jqery更加方便 一个页面想要使用jqery的话,先要引入一下jqery包,jqery包从网上下一个就可以, ...

  6. 利用snowfall.jquery.js实现爱心满屏飞

    小颖在上一篇一步一步教你用CSS画爱心中已经分享一种画爱心的方法,这次再分享一种方法用css画爱心,并利用snowfall.jquery.js实现爱心满屏飞的效果. 第一步: 利用伪元素before和 ...

  7. node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理

    一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...

  8. JS正则表达式常用总结

    正则表达式的创建 JS正则表达式的创建有两种方式: new RegExp() 和 直接字面量. //使用RegExp对象创建 var regObj = new RegExp("(^\\s+) ...

  9. 干货分享:让你分分钟学会 JS 闭包

    闭包,是 Javascript 比较重要的一个概念,对于初学者来讲,闭包是一个特别抽象的概念,特别是ECMA规范给的定义,如果没有实战经验,很难从定义去理解它.因此,本文不会对闭包的概念进行大篇幅描述 ...

随机推荐

  1. php.basic.functions

    array_unshift call_user_func_array闭包 下面是学院的代码 class Container { protected $binds; protected $instanc ...

  2. Golang modules包依赖管理工具

    初始化 执行go mod  init module-name,其中module-name为包名字,执行完后会生成go.mod文件,如下 module module-name go 1.13 包管理 使 ...

  3. Swift 闭包使用(循环引用...)

    class networkTool: NSObject { //定义一个可选类型的闭包,用小括号()?括起闭包 var finishedCallBack2:((_ jsonData:String)-& ...

  4. 二、【未来】React环境安装:npx

    搭建React的开发环境的第二种方法(新-未来推荐): https://reactjs.org/docs/create-a-new-react-app.html 一. npx简介: 1. npm v5 ...

  5. ELK 介绍

    章节 ELK 介绍 ELK 安装Elasticsearch ELK 安装Kibana ELK 安装Beat ELK 安装Logstash ELK是什么? ELK是3个开源产品的组合: Elastics ...

  6. Sublime 一些常用快捷键

    Sublime插件安装和使用-----------------------------最常用的1.新建文件-输入"html:xt"后 按"Ctrl+E键"或 & ...

  7. 轻量级UILabel分段点击扩展更新啦

    http://www.code4app.com/thread-31445-1-1.html Tag: 项目介绍: YBAttributeTextTapAction 一行代码添加文本点击事件 效果图 S ...

  8. 路飞学城—Python爬虫实战密训班 第三章

    路飞学城—Python爬虫实战密训班 第三章 一.scrapy-redis插件实现简单分布式爬虫 scrapy-redis插件用于将scrapy和redis结合实现简单分布式爬虫: - 定义调度器 - ...

  9. Android自定义View——刮刮卡效果

    想要红包的实现效果的可以关注我的博客,仿饿了么红包 下层图片:我们的红包的图片 上层图片:有两部分 一部分是灰色背景 一部分是拥有透明度为0,并且模式为交集的画笔 使用滑动监听,滑动时,用透明度为0的 ...

  10. PAT 2018 秋

    A 1148 Werewolf - Simple Version 思路比较直接:模拟就行.因为需要序列号最小的两个狼人,所以以狼人为因变量进行模拟. #include <cstdio> # ...