在JS

时间:2015-04-22 09:59:44

标签: javascript arrays

假设我有以下数组:

var first = [
    { id: 1, name: 'first' },
    { id: 2, name: 'second' },
    { id: 3, name: 'third' }
]

var second = [
    { id: 2, field: 'foo2' },
    { id: 3, field: 'foo3' },
    { id: 4, field: 'foo4' }
]

var third = [
    { id: 2, data: 'some2' },
    { id: 5, data: 'some5' },
    { id: 6, data: 'some6' }
]

我想合并它们以获得以下结果:

var result = [
    { id: 1, name: 'first',   field: undefined, data: undefined },
    { id: 2, name: 'second',  field: 'foo2',    data: 'some2' },
    { id: 3, name: 'third',   field: 'foo3',    data: undefined },
    { id: 4, name: undefined, field: 'foo4',    data: undefined },
    { id: 5, name: undefined, field: undefined, data: 'some5' },
    { id: 6, name: undefined, field: undefined, data: 'some6' }
]

我怎么能用JavaScript做到这一点?

4 个答案:

答案 0 :(得分:0)

没有简单的解决方案可以满足您的需求。这是我的建议。

{6/2/2010 12:00:00 AM}
    Date: {6/2/2010 12:00:00 AM}
    Day: 2
    DayOfWeek: Wednesday
    DayOfYear: 153
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 6
    Second: 0
    Ticks: 634110336000000000
    TimeOfDay: {00:00:00}
    Year: 2010

答案 1 :(得分:0)

你应该获得所有现有的密钥,并在创建带有填充“空”键的新对象后:

function mergeArrays(){
    var keys = {};
    //save all existed keys
    for(var i=arguments.length;--i;){
        for(var j=arguments[i].length;--j;){
            for(var key in arguments[i][j]){
                keys[key] = true;
            }
        }
    }

    var res = [];
    for(var i=arguments.length;--i;){
        for(var j=arguments[i].length;--j;){
            //set clone of object
            var clone = JSON.parse(JSON.stringify(arguments[i][j]));
            for(var key in keys){
                if(!(key in clone)){
                    clone[key] = undefined;
                }
            }
            res.push(clone);
        }
    }

    return res;
}

https://jsfiddle.net/x3b0tk3g/

答案 2 :(得分:0)

可能有一种更短的方法来解决这个问题,但这包括所有步骤,包括确保如果找不到undefined的默认属性。它还可以使用任意数量的输入数组,如果现有对象中的键尚未覆盖,您可以指定所需的默认键,因此可以满足您的需求。

// merges the key/values of two objects
function merge(a, b) {
    var key;
    if (a && b) {
        for (key in b) {
            if (b.hasOwnProperty(key)) {
                a[key] = b[key];
            }
        }
    }
    return a;
}

function concatenate() {
    var result = [];
    var args = arguments[0];
    for (var i = 0, l = args.length; i < l; i++) {
        result = result.concat(args[i]);
    }
    return result;
}

// return a default object
function getDefault() {
    return {
        id: undefined,
        name: undefined,
        data: undefined,
        field: undefined
    };
}

// loop over the array and check the id. Add the id as a key to
// a temporary pre-filled default object if the key
// doesn't exist, otherwise merge the existing object and the
// new object
function createMergedArray(result) {
    var temp = {};
    var out = [];
    for (var i = 0, l = result.length; i < l; i++) {
        var id = result[i].id;
        if (!temp[id]) temp[id] = getDefault();
        merge(temp[id], result[i]);
    }

    // loop over the temporary object pushing the values
    // into an output array, and return the array
    for (var p in temp) {
        out.push(temp[p]);
    }
    return out;
}

function mergeAll() {

    // first concatenate the objects into a single array
    // and then return the results of merging that array
    return createMergedArray(concatenate(arguments));
}

mergeAll(first, second, third);

DEMO

答案 3 :(得分:0)

小提琴:http://jsfiddle.net/bs20jvnj/2/

 function getByProperty(arr, propName, propValue) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i][propName] == propValue) return arr[i];
        }
    }
var limit = first.length + second.length + third.length;
var res = [];
for (var i = 1; i < limit; i++) {

    var x = $.extend({}, getByProperty(first, "id", i), getByProperty(second, "id", i), getByProperty(third, "id", i));
    console.log(x["id"]);
    if (x["id"] === undefined) x["id"] = i;
    res.push(x);
}

console.log(res);