本文介绍了如何使用javascript合并对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下
$scope.Marketing = [{
'ProductId':1,
'ProductName':'Product 1',
'ProductDescription':'Product Description 1'
},
{
'ProductId':2,
'ProductName':'Product 2',
'ProductDescription':'Product Description 2'
}];
$scope.Finance=[{
'ProductId':1,
'Price':'$200.00'
},
{
'ProductId':2,
'Price':'$100.00'
}];
$scope.Inventory=[{
'ProductId':1,
'StockinHand:':26
},
{
'ProductId':2,
'StockinHand':40
}];
我希望输出
我的合并功能在这里
$scope.tempresult=merge($scope.Marketing,$scope.Finance);
$scope.result=merge($scope.tempresult,$scope.Inventory);
function merge(obj1,obj2){ // Our merge function
var result = {}; // return result
for(var i in obj1){ // for every property in obj1
if((i in obj2) && (typeof obj1[i] === "object") && (i !== null)){
result[i] = merge(obj1[i],obj2[i]); // if it's an object, merge
}else{
result[i] = obj1[i]; // add it to result
}
}
for(i in obj2){ // add the remaining properties from object 2
if(i in result){ //conflict
continue;
}
result[i] = obj2[i];
}
return result;
}
但输出为
缺少第一手股票的价值。请帮助
The value for first Stock In Hand is missing. Please help
我犯的错误是什么?
如果有人帮助我弄清楚我在功能上做了什么错,我会更高兴。我太累了。提前致谢
I would be more glad if somebody helps me in figuring out what wrong I am doing in my function. I am too tired. Thanks in advance
编辑
推荐答案
您可以使用Jquery.extend属性,看一下plnkr代码
you could use Jquery.extend property, have a look at the plnkr code
$scope.result=merge($scope.Marketing, $scope.Finance,$scope.Inventory);
function merge(obj1,obj2, obj3){
return $.extend(true, obj1,obj2,obj3)
}
};
这篇关于如何使用javascript合并对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!