Angular LoadAsh - 过滤不同类型的多个对象上的字段匹配的记录

时间:2016-08-24 06:07:29

标签: javascript angularjs

我一直在努力学习loadash以及如何使用一些更高级的技巧正确地提取我想要的数据。单个对象和查找非常简单,但是我试图通过groupId拉出所有数组记录,如果该groupId存在于另一个不相同的对象中。

例如:     对象的通用JSON示例,每个都是记录数组。

var results = [];
_.forEach(Groups, function(g) {
    var found _.find(Options, g, function(option, group) {
         return option.groupId === group.groupId;
    })
    results.push(found);
});

我遇到的问题是只有在loadash中的groups数组中存在groupId时才会提取所有选项。

我尝试了一些像

这样的东西
public class ListViewActivity extends Activity implements LocationListener {
    // Log tag
    private static final String TAG = ListViewActivity.class.getSimpleName();
    // change here url of server api
    // private static final String url = "https://comida-95724.herokuapp.com/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
    private ProgressDialog pDialog;
    private static String url;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
        //update coordinates every 30 seconds
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 1, this);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Movie movie = movieList.get(position);
                Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
                intent.putExtra("name", movie.getName());
                intent.putExtra("average_ratings", movie.getAverage_ratings());
                intent.putExtra("full_address", movie.getAddress());
                intent.putExtra("image_url", movie.getThumbnailUrl());
                intent.putExtra("cuisine", movie.getCuisine());
                intent.putExtra("cost", movie.getCost());
                startActivity(intent);

            }
        });

        listView.setAdapter(adapter);
        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Please Keep patience.Its loading...");

        pDialog.show();

    }
    private void loadJson(double latitude, double longitude) {
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);
        adapter.clear();
        url = "https://comida-95724.herokuapp.com/api/v1/restaurants?per_page=5&km=1&location=true&lat="+latitude+"&long="+longitude;
        // Creating volley request obj
        JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
                url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                JSONArray

                        restaurantsJSONArray = null;
                try {
                    restaurantsJSONArray = response.getJSONArray("restaurants");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                hidePDialog();
                // Parsing json
                for (int i = 0; i < restaurantsJSONArray.length(); i++) {
                    try {

                        JSONObject obj = restaurantsJSONArray.getJSONObject(i);
                        Movie movie = new Movie();
                        //movie.setTitle(obj.getString("title"));
                        movie.setName(obj.getString("name"));
                        //movie.setThumbnailUrl(obj.getString("image"));
                        movie.setThumbnailUrl(obj.getString("org_image_url"));
                        movie.setAverage_ratings(obj.getString("average_ratings"));
                        movie.setCuisine(obj.getString("cuisine"));
                        movie.setAddress(obj.getJSONObject("address").getString("area"));
                        // movie.setAddress(obj.getJSONObject("address").getString("full_address"));
                        movie.setCost(obj.getString("cost"));
                        movie.setDistance(obj.getDouble("distance"));

                        JSONArray textJSONArray = obj.getJSONArray("restaurant_offers");

                        for (int j = 0; j < textJSONArray.length(); j++) {


                            JSONObject txtobj = textJSONArray.getJSONObject(j);
                            //obj.getJSONArray("restaurant_offers").getJSONObject(0).getSt‌​ring("text");
                            //movie.settext(obj.getJSONArray("restaurant_offers").getJSONObject(j).getSt‌​ring("text"));
                            movie.settext(txtobj.getString("text"));
                        }


                        // movie.settext(obj.getString("text"));
                        movieList.add(movie);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });


        AppController.getInstance().addToRequestQueue(movieReq);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
       //client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
       // client = new GoogleApiClient.Builder(this).addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this).addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this).addApi(AppIndex.API).build();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "ListView Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.comida/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "ListView Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.comida/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    @Override
    public void onLocationChanged(Location location) {
        //whenever location is updated call method that will load JSON
        loadJson(location.getLatitude(),location.getLongitude());
        Log.d("hello", location.getLatitude() + " " + location.getLongitude());
    }



    @Override
    public void onStatusChanged(String provider, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

我没有太多的运气找出最好的方法来过滤这些。

任何言语,如果智慧会受到赞赏,谢谢!

1 个答案:

答案 0 :(得分:3)

这样的事情应该有效,

var result = _.filter(Options, function(o) { 
  return _.filter(Groups, function(g) { return g.groupId == o.groupid; }).length > 0;
});

实际上我认为内部搜索会在find中表现更好,因为它会返回第一场比赛,但不确定

var result = _.filter(Options, function(o) { 
  return _.find(Groups, { 'groupId': o.groupid });
});

希望这会有所帮助。