JavaScript | JSON对象按值合并和排序

时间:2013-02-07 09:34:02

标签: javascript json

我有以下json abjects,我喜欢将它们合并到一个对象中,并根据'minute'值缩短子对象。这是可以用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

2 个答案:

答案 0 :(得分: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;
    }
    

答案 1 :(得分: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);