使用新键合并特定对象数组

时间:2015-12-10 17:35:33

标签: javascript jquery lodash

我正在尝试将两个对象合并为一个(obj1和obj2合并为objResult):

var obj1 = {
 0: [{obj1key1: 'obj1value1'}, {obj1key2: 'obj1value2'}],
 1: [{obj1key3: 'obj1value3'}, {obj1key4: 'obj1value4'}],
 2: [{obj1key5: 'obj1value5'}, {obj1key6: 'obj2value6'}]
};
var obj2 = {
 0: [{obj2key1: 'obj2value1'}, {obj2key2: 'obj2value2'}],
 1: [{obj2key3: 'obj2value3'}, {obj2key4: 'obj2value4'}],
 2: [{obj2key5: 'obj2value5'}, {obj2key6: 'obj2value6'}]};
var objResult = {
 0: {
   0: [{obj1key1: 'obj1value1'}, {obj1key2: 'obj1value2'}],
   1: [{obj2key1: 'obj2value1'}, {obj2key1: 'obj2value1'}]
 },
 1: {
   0: [{obj1key3: 'obj1value3'}, {obj1key4: 'obj1value4'}],
   1: [{obj2key3: 'obj2value3'}, {obj2key4: 'obj2value4'}]
 },
 2: {
   0: [{obj1key5: 'obj1value5'}, {obj1key6: 'obj1value6'}],
   1: [{obj2key5: 'obj2value5'}, {obj2key6: 'obj2value6'}]
 }
}

我尝试了jQuery和lodash的合并功能但没有成功。 您能建议将这两个对象合并为一个的最佳方法吗?使用普通的JS或jquery / lodash。

3 个答案:

答案 0 :(得分:1)

迭代其中一个对象中的键,对于每个对象,将结果对象上的该键设置为包含两个原始对象的值的对象。

function merge(obj1, obj2) {
    var objResult = {};

    Object.keys(obj1).forEach(function(key) {
        objResult[key] = {
            0: obj1[key],
            1: obj2[key]
        }
    })

    return objResult;
}

这假设两个对象具有相同的密钥集。如果他们不这样做,你可以迭代两个对象的键,这将设置undefined作为该对象不包含该键时的值。

Demo

答案 1 :(得分:1)

假设这两个对象具有相同的大小(长度)



var obj1 = {
 0: [{obj1key1: 'obj1value1'}, {obj1key2: 'obj1value2'}],
 1: [{obj1key3: 'obj1value3'}, {obj1key4: 'obj1value4'}],
 2: [{obj1key5: 'obj1value5'}, {obj1key6: 'obj2value6'}]
};
var obj2 = {
 0: [{obj2key1: 'obj2value1'}, {obj2key2: 'obj2value2'}],
 1: [{obj2key3: 'obj2value3'}, {obj2key4: 'obj2value4'}],
 2: [{obj2key5: 'obj2value5'}, {obj2key6: 'obj2value6'}]};

var result = {};
_.each(obj1, function(obj, key){
   result[key] = [];
   result[key].push(obj);
   result[key].push(obj2[key]);    
});

$('body').append('<pre><code>' + JSON.stringify(result) + '</code></pre>');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://lodash.com/_js/lodash.js"></script>
&#13;
&#13;
&#13;

当然,如果你有多个长度,你需要迭代更大的长度并跟踪大小

答案 2 :(得分:1)

这是一个简单的JS示例,可以管理不同大小的对象。

var obj1 = {
 0: [{obj1key1: 'obj1value1'}, {obj1key2: 'obj1value2'}],
 1: [{obj1key3: 'obj1value3'}, {obj1key4: 'obj1value4'}],
 2: [{obj1key5: 'obj1value5'}, {obj1key6: 'obj2value6'}]
};
var obj2 = {
 0: [{obj2key1: 'obj2value1'}, {obj2key2: 'obj2value2'}],
 1: [{obj2key3: 'obj2value3'}, {obj2key4: 'obj2value4'}],
 2: [{obj2key5: 'obj2value5'}, {obj2key6: 'obj2value6'}]};

var obj3 = [obj1, obj2].reduce(function(result, obj, objNum){
  return Object.keys(obj).reduce(function(result, k){
    result[k] = result[k] || {};
    result[k][objNum] = obj[k];
    return result;
  }, result);
}, {});

console.log(obj3);