按键组合对象数组

时间:2016-07-30 07:16:08

标签: javascript jquery arrays

我试图在我的案例id中按键组合/合并2个对象数组。

目的:

  1. 我期待一个结果,其中我将包含所有带有ID 1,2,3,4的对象的数组
  2. 合并顺序不应影响结果中的对象数量,例如combine(arr1,arr2)combine(arr2,arr1)应该包含具有相同数量对象的数组
  3. 合并顺序只能影响结果对象,例如在combine(arr1,arr2) arr2键的情况下,值对可以覆盖arr1键,值就像深度jquery extend $ .extend(true,arr1ObJ,arr2ObJ);
  4. JSFIDDLE:https://jsfiddle.net/bababalcksheep/u2c05nyj/

    示例数据:

    var arr1 = [{
      id: 1,
      name: "fred",
      title: "boss"
    }, {
      id: 2,
      name: "jim",
      title: "nobody"
    }, {
      id: 3,
      name: "bob",
      title: "dancer"
    }];
    var arr2 = [{
      id: 1,
      wage: "300",
      rate: "day"
    }, {
      id: 2,
      wage: "10",
      rate: "hour"
    }, {
      id: 4,
      wage: "500",
      rate: "week"
    }];
    var Result = [{
      "id": 1,
      "name": "fred",
      "title": "boss",
      "wage": "300",
      "rate": "day"
    }, {
      "id": 2,
      "name": "jim",
      "title": "nobody",
      "wage": "10",
      "rate": "hour"
    }, {
      id: 3,
      name: "bob",
      title: "dancer" 
    }, {
      id: 4,
      wage: "500",
      rate: "week"
    }];
    

2 个答案:

答案 0 :(得分:2)

这是一个解决方案。它基本上遍历arr2的每个元素,并检查是否有一个匹配ID为arr1的元素。如果是这样,它会使用arr2的值更新arr1中的匹配元素。如果没有匹配,它只是将arr2中的元素推送到arr1。

var arr1 = [{id: 1,name: 'fred',title: 'boss'}, 
            {id: 2,name: 'jim',title: 'nobody'}, 
            {id: 3,name: 'bob',title: 'dancer'}];

var arr2 = [{id: 1,wage: '300',rate: 'day'}, 
            {id: 2,wage: '10',rate:'hour'},
            {id: 4,wage: '500',rate: 'week'}];

function combineArrays(arr1, arr2) {
  for(var i = 0; i < arr2.length; i++) {
    // check if current object exists in arr1
    var idIndex = hasID(arr2[i]['id'], arr1);
    if(idIndex >= 0){
      //update
      for(var key in arr2[i]){
        arr1[idIndex][key] = arr2[i][key];
      }
    } else {
      //insert
      arr1.push(arr2[i]);
    }
  }

  return arr1;
}

//Returns position in array that ID exists
function hasID(id, arr) {
  for(var i = 0; i < arr.length; i ++) {
    if(arr[i]['id'] === id)
    {
      return i;
    }
  }

  return -1;
}

var combine = combineArrays(arr1, arr2);
output(combine);

/* pretty Print */
function output(inp) {
  var str = JSON.stringify(inp, undefined, 4);
  $('body').append($('<pre/>').html(str));
}

var arr1 = [{
  id: 1,
  name: 'fred',
  title: 'boss'
}, {
  id: 2,
  name: 'jim',
  title: 'nobody'
}, {
  id: 3,
  name: 'bob',
  title: 'dancer'
}];

var arr2 = [{
  id: 1,
  wage: '300',
  rate: 'day'
}, {
  id: 2,
  wage: '10',
  rate: 'hour'
}, {
  id: 4,
  wage: '500',
  rate: 'week'
}];

function combineArrays(arr1, arr2) {
  for (var i = 0; i < arr2.length; i++) {
    var idIndex = hasID(arr2[i]['id'], arr1);
    if (idIndex >= 0) {
      for (var key in arr2[i]) {
        arr1[idIndex][key] = arr2[i][key];
      }
    } else {
      arr1.push(arr2[i]);
    }
  }

  return arr1;
}

function hasID(id, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]['id'] === id) {
      return i;
    }
  }

  return -1;
}

var combine = combineArrays(arr1, arr2);
output(combine);

/* pretty Print */
function output(inp) {
  var str = JSON.stringify(inp, undefined, 4);
  $('body').append($('<pre/>').html(str));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

如何做到这一点:

function combineArrays(arr1, arr2, keyFunc) {
    var combined = [],
        keys1 = arr1.map(keyFunc),
        keys2 = arr2.map(keyFunc),
        pos1 = keys1.map(function (id) {
            return keys2.indexOf(id);
        }),
        pos2 = keys2.map(function (id) {
            return keys1.indexOf(id);
        });

    arr1.forEach(function (item, i) {
        combined.push( $.extend(item, arr2[pos1[i]]) );
    });
    arr2.forEach(function (item, i) {
        if (pos2[i] === -1) combined.push( item );
    });
    return combined;    
}

用作

var combine = combineArrays(arr1, arr2, function (item) {
    return item.id;
});

var arr1 = [
    { id: 1, name: 'fred', title: 'boss' },
    { id: 2, name: 'jim', title: 'nobody' },
    { id: 3, name: 'bob', title: 'dancer' }
];
var arr2 = [
    { id: 1, wage: '300', rate: 'day' },
    { id: 2, wage: '10', rate: 'hour' },
    { id: 4, wage: '500', rate: 'week' }
];

function combineArrays(arr1, arr2, keyFunc) {
    var combined = [],
        keys1 = arr1.map(keyFunc),
        keys2 = arr2.map(keyFunc),
        pos1 = keys1.map(function (id) {
            return keys2.indexOf(id);
        }),
        pos2 = keys2.map(function (id) {
            return keys1.indexOf(id);
        });

    arr1.forEach(function (item, i) {
        combined.push( $.extend(item, arr2[pos1[i]]) );
    });
    arr2.forEach(function (item, i) {
        if (pos2[i] === -1) combined.push( item );
    });
    return combined;
}

var combine = combineArrays(arr1, arr2, function (item) {
    return item.id;
});

output(combine);



//
//
//
/* pretty Print */
function output(inp) {
    var str = JSON.stringify(inp, undefined, 4);
    $('body').append($('<pre/>').html(str));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>