简体   繁体   English

使用underscore.js搜索对象数组内部的字符串

[英]Search the String inside array of Objects using underscore.js

I want to search the String inside an object using underscore.js 我想使用underscore.js搜索对象内部的字符串

JSON data JSON数据

{ data:
       [ 
         {'id': 1, 'name': 'New Samsung Galaxy 3' },
         {'id': 2, 'name': 'Samsung Grand'},  
         {'id': 3, 'name': 'Galaxy 3 dress new Arrival'}, 
         {'id': 4, 'name': 'Samsung Galaxy 3 black ' }, 
         {'id': 5, 'name': 'Samsung refrigerators'} 
        ];
 }

Let Suppose I have a keyword Samsung Galaxy 3 . 假设我有一个关键字 Samsung Galaxy 3 I want it return the matching string only. 我希望它仅返回匹配的字符串。

Like This Output : 像这样的输出:

{ data:
       [ 
          {'id': 1, 'name': 'New Samsung Galaxy 3' },
          {'id': 4, 'name': 'Samsung Galaxy 3 black ' }, 
       ];
 }

Use _filter . 使用_filter

var data =
       [ 
         {'id': 1, 'name': 'New Samsung Galaxy 3' },
         {'id': 2, 'name': 'Samsung Grand'},  
         {'id': 3, 'name': 'Galaxy 3 dress new Arrival'}, 
         {'id': 4, 'name': 'Samsung Galaxy 3 black ' }, 
         {'id': 5, 'name': 'Samsung refrigerators'} 
        ];

    _.filter(data, function(item) { 
       return item.name.indexOf("Samsung Galaxy 3") != -1; 
    });

You can use _filter or _where 您可以使用_filter_where

_filter: Return all the elements that pass a truth test. _filter:返回所有通过真相测试的元素。 Similarly as select . select类似。

_where: Convenience version of a common use case of filter . _where: filter的一个常见用例的便捷版本。 Selecting only objects containing specific key:value pairs. 仅选择包含特定key:value对的对象。

http://jsfiddle.net/yqagfLqb/ http://jsfiddle.net/yqagfLqb/

var data =
   [ 
     {'id': 1, 'name': 'New Samsung Galaxy 3' },
     {'id': 2, 'name': 'Samsung Grand'},  
     {'id': 3, 'name': 'Galaxy 3 dress new Arrival'}, 
     {'id': 4, 'name': 'Samsung Galaxy 3 black ' }, 
     {'id': 5, 'name': 'Samsung refrigerators'} 
    ];

_.where(data, function(item) { 
   return item.name.indexOf("Samsung Galaxy 3") != -1; 
});

console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM