1

我有以下 json 对象,我喜欢将它们合并为一个对象,并根据“分钟”值缩短子对象。这对 JavaScript 可行吗?

[Object, Object, Object]
    0: Object
        Live: "188585"
        Minute: "17"
        Player: "Player A"
        Team: "188564"
        __proto__: Object
    1: Object
        Live: "188585"
        Minute: "26"
        Player: "Player B"
        Team: "188564"
        __proto__: Object
    2: Object
        Live: "188585"
        Minute: "77"
        Player: "Player A"
        Team: "188564"
        __proto__: Object
[Object, Object]
    0: Object
        Live: "188585"
        Minute: "31"
        Player: "Player C"
        Team: "188558"
        __proto__: Object
    1: Object
        Live: "188585"
        Minute: "41"
        Player: "Player D"
        Team: "188558"
        __proto__: Object

我喜欢这样的结果:

[Object, Object, Object, Object, Object]
    0: Object
        Live: "188585"
        Minute: "17"
        Player: "Player A"
        Team: "188564"
        __proto__: Object
    1: Object
        Live: "188585"
        Minute: "26"
        Player: "Player B"
        Team: "188564"
        __proto__: Object
    2: Object
        Live: "188585"
        Minute: "31"
        Player: "Player C"
        Team: "188558"
        __proto__: Object
    3: Object
        Live: "188585"
        Minute: "41"
        Player: "Player D"
        Team: "188558"
        __proto__: Object
    4: Object
        Live: "188585"
        Minute: "77"
        Player: "Player A"
        Team: "188564"
        __proto__: Object
4

2 回答 2

2

如果您的两个数组已经按分钟排序,您可以使用“经典”合并算法。如果没有,您可以连接您的数组并使用 Array.sort 对结果进行排序(具有特定的比较功能)。

编辑:这是一个例子:

  1. 如果数组未排序:

    var result = array1.concat(array2);
    result.sort(function(item1, item2) {
        return item1.Minute - item2.Minute;
    });
    
  2. 如果数组是排序的,这里有一个简单的合并函数:

    function merge(array1, array2) {
        var results = [];
        var i = 0, j = 0;
        while (i < array1.length && j < array2.length) {
            if (array1[i].Minute <= array2[j].Minute) {
                results.push(array1[i];
                i++;
            }
            else {
                results.push(array2[j];
                j++;
            }
        }
        while (i < array1.length) {
            results.push(array1[i];
            i++;
        }
        while (j < array2.length) {
            results.push(array2[j];
            j++;
        }
        return results;
    }
    
于 2013-02-07T09:40:36.063 回答
2

更多的对象,它们似乎是对象的数组。如果是这种情况,您可以使用Array.concat进行连接,并使用Array.sort进行排序。

就像是:

// assuming `aba` is the first array, `cd` the second
var result = aba.concat(cd);

result.sort(function(a, b) {
    return a.Minute - b.Minute // implicit conversion in number
});

console.log(result);
于 2013-02-07T09:49:08.680 回答