我有以下
$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;
}
但输出是
缺少第一手股票的价值。请帮忙
我犯的错误是什么?
如果有人帮我弄清楚我在功能上做了什么错,我会更高兴。我太累了。提前致谢
修改
答案 0 :(得分:1)
一种方法是填充其他两个产品缺少属性的产品数组(与产品ID匹配后)。
请参阅:http://jsfiddle.net/zekbxh90/1/ - 并检查控制台输出
代码:
var a = [{
'ProductId': 1,
'ProductName': 'Product 1',
'ProductDescription': 'Product Description 1'
}, {
'ProductId': 2,
'ProductName': 'Product 2',
'ProductDescription': 'Product Description 2'
}];
var b = [{
'ProductId': 1,
'Price': '$200.00'
}, {
'ProductId': 2,
'Price': '$100.00'
}];
var c = [{
'ProductId': 1,
'StockinHand:': 26
}, {
'ProductId': 2,
'StockinHand': 40
}];
// lets add the props from b abd c into a to get the desired result
a.forEach(function (_itemA) {
// get product id in a
var productId = _itemA.ProductId,
matching = false,
prop = false;
// get the matching item in b and add new props to a
b.forEach(function (_itemB) {
if (_itemB.ProductId === productId) merge(_itemA, _itemB);
});
// get the matching item in c and add new props to a
c.forEach(function (_itemC) {
if (_itemC.ProductId === productId) merge(_itemA, _itemC);
});
});
console.log(a);
function merge(_to, _from) {
for (var prop in _from) {
if (!_to.hasOwnProperty(prop) && _from.hasOwnProperty(prop)) _to[prop] = _from[prop];
}
}
答案 1 :(得分:1)
你可以使用Jquery.extend属性,看一下plnkr代码
$scope.result=merge($scope.Marketing, $scope.Finance,$scope.Inventory);
function merge(obj1,obj2, obj3){
return $.extend(true, obj1,obj2,obj3)
}
};