简体   繁体   English

通过 Angular/Javascript 中的成对值分隔数组中的对象?

[英]Separate objects in array by paired values in Angular / Javascript?

I currently have a large array with 120 objects.我目前有一个包含 120 个对象的大型数组。 Each one has an id value, and an opposite_id value, to basically pair two objects.每个都有一个 id 值和一个 reverse_id 值,基本上可以配对两个对象。 What is the best way to loop through each of the objects, and either put each pair in a new array or display the two as a pair?循环遍历每个对象并将每一对放入新数组或将两者显示为一对的最佳方法是什么?

As an example:举个例子:

    Obj1 = {
        id: 1,
        opposite_id: 2,
        descr: "This is the first object"
   },
   Obj2 = {
        id: 2,
        opposite_id: 1,
        descr: "This is the second object"
   },
    Obj3 = {
        id: 3,
        opposite_id: 6,
        descr: "This is the third object"
   }

I would need to ultimately display Obj1 and Obj2 together (ideally with ng-repeat) as a pair while avoiding displaying Obj2 and Obj1 (since it'd be a repeat)...I'm having trouble wrapping my head around how to do this particular action, any help would be much appreciated!我需要最终将 Obj1 和 Obj2 一起显示(理想情况下与 ng-repeat 一起显示),同时避免显示 Obj2 和 Obj1(因为它会重复)......我无法理解如何做这个特殊的行动,任何帮助将不胜感激! Thank you谢谢

Here is one way you could pair them.这是您可以配对它们的一种方法。

 var app = angular.module("app", []); app.controller("controller", function($scope) { var users = [{ "id": 11, "user": { "id": 5, "first_name": "", "last_name": "" }, "opponent": 2 }, { "id": 12, "user": { "id": 6, "first_name": "", "last_name": "" }, "opponent": 3 }, { "id": 13, "user": { "id": 2, "first_name": "", "last_name": "" }, "opponent": 5 }, { "id": 14, "user": { "id": 3, "first_name": "", "last_name": "" }, "opponent": 6 }]; $scope.pairs = []; var alreadyPaired = []; // ids of users that have already been paired for (var i = 0; i < users.length; i++) { var user = users[i]; // if this user hasn't already been paired if (alreadyPaired.indexOf(user.user.id) === -1) { var opponent = null; for (var j = 0; j < users.length; j++) { if (users[j].user.id === user.opponent) { opponent = users[j]; } } $scope.pairs.push({ user1: user, user2: opponent }); alreadyPaired.push(user.user.id); alreadyPaired.push(opponent.user.id); } } });
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="controller"> <h3>Pairs</h3> <table> <thead> <tr> <th>User</th> <th>Opponent</th> </tr> </thead> <tbody> <tr ng-repeat="pair in pairs"> <td>{{pair.user1.user.id}}</td> <td>{{pair.user2.user.id}}</td> </tr> </tbody> </table> </div>

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

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