Javascript:根据其他字段合并两个JSON

时间:2013-10-23 11:29:47

标签: javascript json

我有2个像这样的json输入:

[
  {
    userId: 32159,
    userFirstName: "john",
    userLastName: "doe",
    plans: [ ]
  },
  {
    userId: 32157,
    userFirstName: "dave",
    userLastName: "mess",
    plans: [ ]
  }
]

[
      {
        userId: 32159,
        userFirstName: "john",
        userLastName: "doe",
        results: [ ]
      },
      {
        userId: 32157,
        userFirstName: "dave",
        userLastName: "mess",
        results: [ ]
      }
]

我希望输出为:

[
      {
        userId: 32159,
        userFirstName: "john",
        userLastName: "doe",
        plans: [ ],
        results: [ ]
      },
      {
        userId: 32157,
        userFirstName: "dave",
        userLastName: "mess",
        plans: [ ],
        results: [ ]
      }
 ]

如何在javascript中执行此操作。请帮助。这个userId是一个独特的字段

6 个答案:

答案 0 :(得分:1)

我认为你正试图extend每个对象,这可以通过循环遍历其中一个集合,然后选择相应的对象并扩展它来实现,就像这样......

var collectionA = [], collectionB = [],
    result = [];

$.each(collectionA, function(i, objA) {
    $.each(collectionB, function(j, objB) {
        if (objA.userId === objB.userId) {
            result.push($.extend({}, objA, objB);
            return false;
        }
    });
});

console.log(result);

答案 1 :(得分:0)

使用jQuery扩展函数:

var json1 = [{
    userId: 32159,
    userFirstName: "john",
    userLastName: "doe",
    plans: []
}, {
    userId: 32157,
    userFirstName: "dave",
    userLastName: "mess",
    plans: []
}];

var json2 = [{
    userId: 32157,
    userFirstName: "dave",
    userLastName: "mess",
    results: []
}, {
    userId: 32159,
    userFirstName: "john",
    userLastName: "doe",
    results: []
}];

var jsonCombined = [];

for (i = 0; i < json1.length; i++) {
    for (i2 = 0; i2 < json2.length; i2++) {
        if (json1[i].userId == json2[i2].userId) 
            jsonCombined.push($.extend(json1[i], json2[i2]));
    }
}

console.log(jsonCombined);

小提琴here

答案 2 :(得分:0)

您可以使用下划线-min.js文件,并使用其内置函数

尝试如下
 _.each(json1, function(val1) {
    _.each(json2, function(val2) {
            if (val1.userId = val2.userId) {
                _.extend(val1, val2.results);
            }
        }

    })

  });

答案 3 :(得分:0)

您可以使用纯JavaScript执行此操作。一种解决方案可能看起来像这样。

function copy(obj1, obj2) {
    for (var x in obj1)
        if (obj1.hasOwnProperty(x))
            obj2[x] = obj1[x];
}

function merge(arr1, arr2) {
    var fin = [];

    for (var i = 0; i < arr1.length; i++) {
        fin.push({});
        copy(arr1[i], fin[i]);
    }

    for (var i = 0; i < arr2.length; i++)
        copy(arr2[i], fin[i]);

    return fin;
}

merge(yourfirstobject, yoursecondobject);

答案 4 :(得分:0)

您想要做的事情在功能编程中称为同步处理。 您有两个数据,并且您希望将它们一起处理以获得结果。考虑一下这段代码

http://repl.it/Ll1/1

// Array Array -> Array
// Assume that length of a is equal to length of b
// and items sorted in the right way to match records
function zip(a,b) {
    // Object Object -> Object
    function add_results(item_a,item_b) {
        item_a["results"] = item_b["results"]
        return item_a;
    }
    if(a.length===0) {
        return [];
    } else {
        return [add_results(a[0],b[0])].concat(zip(a.slice(1),b.slice(1)));
    }
}

zip(a,b);

答案 5 :(得分:0)

我将工作分成离散函数:

function mergeObjects(a, b) {
  if (a && b) { for (var key in b) { a[key] = b[key]; } }
  return a;
}

function mergeAndSortArrays(a, b) {
    return a
        .concat(b)
        .sort(function (a, b) { return a.userId - b.userId; });
}

function combine(a, b) {
    var a = mergeAndSortArrays(a, b);
    for (var i = 0, l = a.length - 1; i < l; i++) {
        if (a[i].userId === a[i+1].userId) {
            a[i] = mergeObjects(a[i], a[i+1]);
            a.splice(i+1, 1);
            i--; l--;
        }
    }
    return a;
}

combine(a, b);