jQuery将两个数组对象比较为一个最终的数组对象

时间:2017-10-26 01:29:11

标签: javascript jquery arrayobject

有人可以帮助解决以下问题吗? 我有两个基于模型和序列进行比较的数组对象,只需要输出一个结果。 请参考以下示例。感谢。

ArrayObject1 = [{model:'M1', serial:'S1', file:'F1', other:null},
                {model:'M2', serial:'S2', file:'F2', other:null}];

ArrayObject2 = [{model:'M1', serial:'S1', file:null, other:'F3'},
                {model:'M3', serial:'S3', file:null, other:'F4'}];

ExpectedResult = [{model:'M1', serial:'S1', file:'F1', other:'F3'},
                 {model:'M2', serial:'S2', file:'F2', other:null},
                 {model:'M3', serial:'S3', file:null, other:'F4'}];

2 个答案:

答案 0 :(得分:0)

我不认为jquery提供了一种简单的方法来解决您的问题。这是我的解决方案:

var arr1 = [
	{ model: "M1", serial: "S1", file: "F1", other: null },
	{ model: "M2", serial: "S2", file: "F2", other: null }
];

var arr2 = [
	{ model: "M1", serial: "S1", file: null, other: "F3" },
	{ model: "M3", serial: "S3", file: null, other: "F4" }
];

var arr3 = arr1.concat(arr2);
var result = [];

arr3.forEach(function(item1, index){
	var arr4 = result.filter(function(item2, index){
		return item1.model === item2.model;
	});
	if (arr4.length === 1) {
		for(var prop in item1){
			if (item1.hasOwnProperty(prop)) {
				arr4[0][prop] = (item1[prop] || arr4[0][prop]);
			}
		}
	}else{
		result.push(item1);
	}
});

console.log(result);

这仅适用于最多有2个型号具有相同型号名称才能合并的情况,因为如果有三个'M1'且其中两个具有非空'文件',那么我不知道哪个选择..

答案 1 :(得分:0)

var ExpectedResult = [];
//loop through either of the object array. Since they are of same length, it wouldn't matter which one you choose to loop though.
 for(var i = 0; i < ArrayObject2.length; i++) {
   //check to see if the array element(which are objects) have the same model property
   if(ArrayObject2[i].model === ArrayObject1[i].model){
     //if they are the same, starting switching the values of the file and other properties in either one of the array 
     //I choose ArrayObject2, it won't matter which one you decide to use

     //this chooses which is truthy between file property of ArrayObject2 at index i and file property of ArrayObject1 at index i and assigns it to the file property of ArrayObject2 at index i
     ArrayObject2[i].file = ArrayObject2[i].file || ArrayObject1[i].file;

      //this chooses which is truthy between other property of ArrayObject2 at index i and other property of ArrayObject1 at index i and assigns it to the other property of ArrayObject2 at index i
     ArrayObject2[i].other = ArrayObject2[i].other || ArrayObject1[i].other;

     //push the ArrayObject2 at position i into the ExpectedResult array
     ExpectedResult.push(ArrayObject2[i]);
   }
   //other wise; if the model property differs, just push the ArrayObject1 and ArrayObject2 at index i
   else {
     ExpectedResult.push(ArrayObject1[i]);
     ExpectedResult.push(ArrayObject2[i]);
   }
 }

 ExpectedResult;