[AngularJS] copy, extend, and merge example

熱門文章 (Popular Post)

Posted by : Duran Hsieh 2月 05, 2017

前言

近來因為工作上的需求,開始面對前端(Angularjs)、後端(C# MVC WebAPI)與預存程序(Stored procedure)介接作業。雖然工作分配以後端與預存程序為主,但與前端介接與測試的過程中,個人會去了解前端程式如何撰寫與如何運作,一方面可以加速介接工作與協助處理問題,另一方面也可以學習前端技術。這次所介紹的三個 function,是因為個人不常撰寫前端,連續三次看到皆需要重新查詢其使用方法,特此學習與紀錄,也提供有興趣的朋友參考,若有錯誤或建議請各位先進不吝提出。

copy, extend, and merge.



介紹

angular.copy

deep copy,完整的將 SourceA  的內容,複製到 DestinationA 中,如下所示:
var SourceA = {'name':'Ina', 'age':'18'};
var DestinationA = {};
angular.copy(SourceA, DestinationA);
console.log(DestinationA);
//result:{ age: "18", name: "Ina" }

如果 DestinationA 有內容的時候,SourceA  會完全覆蓋 DestinationA 內容,如下所示:
var SourceB = {'name':'Ina', 'age':'18'};
var DestinationB = {'name':'Duran', 'age':'30', 'skill':'program'};
angular.copy(SourceB, DestinationB);
console.log(DestinationB);
//result:{ age: "18", name: "Ina" }


angular.extend

shallow copy,extend 與 copy 有點類似,但其實很不一樣,如下面範例所示,你會發現與 copy 結果相同:
var SourceC = {'name': 'Ina', 'age' : '18'};
var DestinationC = {};
angular.extend(DestinationC, SourceC);
console.log(DestinationC);
//result:{ age: "18", name: "Ina" }

但實際上,extend可以有多個來源物件(Source),且後者(Source2)會取代前者(Source1)相同性質內容,如下所示:
var SourceE1 = {'name': 'Ina', 'age' : '18'};
var SourceE2 = {'name': 'Tomaya', 'skill':'swim'};
var DestinationE = {};
angular.extend(DestinationE, SourceE1, SourceE2);
console.log(DestinationE);
//result:{  age: "18",  name: "Tomaya",  skill: "swim"}

若 Destination 有內容,也會以取代相同性質,如下所示:
var SourceD = {'name': 'Ina', 'age' : '18'};
var DestinationD = {'name':'Duran', 'age':'30', 'skill':'program'};
angular.extend(DestinationD, SourceD);
console.log(DestinationD);
//result: {  age: "18",  name: "Ina",  skill: "program" }
註:您需要將要保留的資料放置在最後,以避免被取代。


angurlar.merge

deep copy 物件內容,這個1.4+版本以上推出的merge功能,幾乎與 extend 的作用幾乎一模一樣,如下所示
var SourceF1 = {'name': 'Ina', 'age' : '18'};
var SourceF2 = {'name': 'Tomaya', 'skill':'swim'};
var DestinationF = {};
angular.merge(DestinationF, SourceF1, SourceF2);
console.log(DestinationF);
//result:{  age: "18",  name: "Tomaya",  skill: "swim"}

但在相同物件情況下,extend 並不會複製獨立物件內容,如下所示:
var src1 = { pet: { name: 'Dog', age: 2, weight: 5 } };
var src2 = { pet: { name: 'Cat', age: 3 } };
var dst = {};
console.log(angular.extend(dst, src1, src2));
//result: {  pet: {  age: 3,    name: "Cat"  } }

var src1 = { pet: { name: 'Dog', age: 2, weight: 5 } };
var src2 = { pet: { name: 'Cat', age: 3 } };
var dst = {};
console.log(angular.merge(dst, src1, src2));
//result: {  pet: {  age: 3,    name: "Cat",  weight: 5 } }
您可以參考 http://davidcai.github.io/blog/posts/copy-vs-extend-vs-merge/ ,內有詳細的範例說明。



範例

https://jsbin.com/kunuxe/3/edit?js,console
(merge 與 extend 比較範例改編自David Cai | Blog )






Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Duran Hsieh @ Matsurigoto - Date A Live - Powered by Blogger - Designed by Johanes Djogan -