[英]How to merge objects using 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;
}
但輸出是
缺少 first Stock In Hand 的值。
我犯了什么錯誤?
一種方法是填充一組產品,其中缺少其他兩個產品的屬性(在與產品 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];
}
}
你可以使用 Jquery.extend 屬性,看看 plnkr 代碼
$scope.result=merge($scope.Marketing, $scope.Finance,$scope.Inventory);
function merge(obj1,obj2, obj3){
return $.extend(true, obj1,obj2,obj3)
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.