简体   繁体   English

使用下划线从数组值中过滤json

[英]filter json from array values with underscore

I have an array of object that is need to create a filter on. 我有一个对象数组,需要在其上创建过滤器。 The list contains an owner_id property in the JSON... 该列表在JSON中包含一个owner_id属性...

At the moment im just looping all in the array, however the list should NOT take the ones where owner_id is equal to one of the values in my filterarray: 目前,我只是循环访问数组中的所有内容,但是该列表不应该使用owner_id等于我的filterarray中的值之一的那些:

var filter = "[14657612, 2215375794]";

            $.ajax({
                url: 'myEndPOint',
                dataType: 'json',
                success: function(data) {
                    var media = data.media;
                    var arr = [];

                    _.filter(media, function(val){
                         //The magic should happen here, only return items that has'nt got an val.owner_id that is in "filter" array
                    });

                    for(i=0; i < media.length; i++) {
                        var thumb = media[i].thumbnail;
                        var html = "<li><img src=" + thumb + " /></li>";
                        arr.push(html);
                    }
                    $(".social-ribbon-target").append(arr);
                    $(".loading").css("display", "none");*/

                },
                error: function(error) {
                    console.log("error");
                }
            });

The magic should happen here 魔术应该在这里发生

It is actually not magic, but a function that returns true or false whether the item should be in the returned array. 实际上这不是魔术,而是一个返回truefalse的函数,该项目是否应位于返回的数组中。

Assuming that your filter is an array and not a string as it is right now (otherwise you have to parse it with filter_arr = JSON.parse(filter) ) you may want to write your filtering function like this: 假设您的过滤器是一个数组,而不是现在的字符串(否则您必须使用filter_arr = JSON.parse(filter)对其进行解析),您可能想要编写如下的过滤函数:

 var filter = ["one", "two", "three"]; var media = [{owner_id: "one"}]; console.log(_.filter(media, function(item){ return filter.indexOf(item.owner_id) >= 0; })) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

You defined filter has a string, instead of an array. 您定义的filter具有字符串,而不是数组。

Change: 更改:

var filter = "[14657612, 2215375794]";

To: 至:

var filter = [14657612, 2215375794];

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

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