Linq.js得到子项目

时间:2015-11-16 16:08:37

标签: javascript jquery json linq linq.js

我正在使用Linq.js从数组中的JSON对象获取元素的子集。 我有一个JSON对象数组,如下所示:

var result = Enumerable.From(data)  
    .Where("$.price > 2")
    .Select("$.price")  
    .ToArray();

我可以按价格过滤:

AngularJS

但是我必须使用 Linqs.js 过滤并获得红色的所有 ID

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用LINQ:



var data = [ { "buy": "Buy", "type": "list", "total": 0, "product": [ { "id": "12345", "title": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.", "description": "Lorem ipsum dolor sit amet, consectetuer...", "price": "9,95", "modelo": [ { "stock": "Y", "color": "red" }, { "stock": "Y", "color": "blue" } ], "Valor": 4.571429, "Comments": 7 }, { "id": "78945", "title": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.", "description": "Lorem ipsum dolor sit amet, consectetuer...", "price": "7,95", "modelo": [ { "stock": "Y", "color": "green" }, { "stock": "Y", "color": "red" } ], "Valor": 7.345256, "Comments": 12 } ] } ],
    result = Enumerable.From(data[0].product)
        .Where("($.modelo).some(function (x) { return x.color === 'red'; })")
        .OrderBy("$.id")
        .Select("$.id")
        .ToArray();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
&#13;
&#13;
&#13;

或简单的Javascript,包含Array.prototype.filter()Array.prototype.some()Array.prototype.map()

&#13;
&#13;
var data = [ { "buy": "Buy", "type": "list", "total": 0, "product": [ { "id": "12345", "title": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.", "description": "Lorem ipsum dolor sit amet, consectetuer...", "price": "9,95", "modelo": [ { "stock": "Y", "color": "red" }, { "stock": "Y", "color": "blue" } ], "Valor": 4.571429, "Comments": 7 }, { "id": "78945", "title": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.", "description": "Lorem ipsum dolor sit amet, consectetuer...", "price": "7,95", "modelo": [ { "stock": "Y", "color": "green" }, { "stock": "Y", "color": "red" } ], "Valor": 7.345256, "Comments": 12 } ] } ],
    result = data[0].product.filter(function (a) {
        return a.modelo.some(function (b) {
            return b.color === 'red';
        });
    }).map(function (a) { return a.id; });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;