javascript
JavaScript编程知识
JavaScript編程知識
1、從陣列中刪除重復(fù)項
數(shù)組:這是一些方便的方法,可用于從數(shù)組中刪除重復(fù)項。
1、使用lodash
let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let arrayuniq = _.uniq(array);//[2, 1, 5, 6, 7, 8, 9, 10]2、使用filter
let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let list = array.filter((x, i, a) => a.indexOf(x) == i); //[2, 1, 5, 6, 7, 8, 9, 10]3、使用set
let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let setuniq = [...new Set(array)]; //[2, 1, 5, 6, 7, 8, 9, 10]2、從對象數(shù)組中刪除重復(fù)項
對象數(shù)組:這是一些方便的方法,可用于從對象數(shù)組中刪除重復(fù)項。
1、使用lodash
let users = [ { id: 1, name: "ted" }, { id: 1, name: "bob" }, { id: 3, name: "sara" }, { id: 4, name: "test" }, { id: 4, name: "test" }, { id: 5, name: "abc" } ]; let uniqueUsersByID = _.uniqBy(users, "id"); //[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]我們可以使用此代碼檢查具有多個屬性的唯一數(shù)據(jù)。
const uniquewithMultipleProperties = _.uniqWith(users,(a, b) => a.id === b.id || a.name === b.name ); //[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]2、使用filter
let filteruniquebyID = users.filter((v, i, a) => a.findIndex(t => t.id === v.id) === i ); //[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]我們可以使用此代碼檢查具有多個屬性的唯一數(shù)據(jù)。
let filteruniquebyIDName = users.filter((v, i, a) => a.findIndex(t => t.id === v.id || t.name === v.name) === i ); //[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]3、使用set
var set1 = Array.from( users.reduce((m, t) => m.set(t.id, t), new Map()).values() ); //[{"id":1,"name":"bob"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]如果你還想了解更多,你可以查看此地址內(nèi)容:https://stackblitz.com/edit/remove-duplicates-arrayofobjects
3、在數(shù)組中查找一個項目
以下是在數(shù)組中查找項目的一些方法。
1、includes:此方法確定數(shù)組在條目中是否包含某個值,是返回true值還是false值。
console.log(array.includes(2)); // returns true2、 every:此方法測試數(shù)組中的所有元素是否通過提供的功能實現(xiàn)的測試。它返回一個布爾值。
let testevery1 = array.every(val=> val>3); //false3、some:此方法測試數(shù)組中的至少一個元素是否通過了由提供的函數(shù)實現(xiàn)的測試。它返回一個布爾值。
let testsome1 = array.some(val=> val>3); //true4、lodash包括:檢查是否value在中。collection返回true是否value找到,否則返回false。
let lodashtest9 =_.includes(array, 1); // true let lodashtest10 =_.includes(array, 3, 2); // false5、findIndex:此方法返回滿足提供的測試功能的數(shù)組中第一個元素的索引。否則,它返回-1,表明沒有任何元素通過測試。
let testindex = array.findIndex(val => val > 1); //06、find:此方法返回提供的數(shù)組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則返回undefined。
let testfind = array.find(el => (el > 2)); //57、 filter:此方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
let testfilter1 = array.filter(val=> val>3); //[5, 6, 7, 8, 9, 9, 10]8、map:此方法創(chuàng)建一個新數(shù)組,其中填充了對調(diào)用數(shù)組中每個元素調(diào)用提供的函數(shù)的結(jié)果。
let val = []; array.map(item => { if(item >= 3) val.push(item); }); //[5, 6, 7, 8, 9, 9, 10]你可以查看更多內(nèi)容:https://stackblitz.com/edit/find-item-array
4、在對象數(shù)組中找到一個項目
這些是可用于在對象數(shù)組中查找項目的方法。
1、every:此方法測試數(shù)組中的所有元素是否通過提供的功能實現(xiàn)的測試。它返回一個布爾值。
let testevery2 = users.every(val=> val.id>3); //false2、some:此方法測試數(shù)組中的至少一個元素是否通過了提供的功能實現(xiàn)的測試。它返回一個布爾值。
let testsome2 = users.some(val=> val.id>3); //true3、 lodash includes:判斷在collection中返回的值,如果可以在value找到,則返回true,否則返回false。
let lodashtest11 =_.includes({ 'a': 1, 'b': 2 }, 1); //true let lodashtest12 =_.includes('abcd', 'bc'); //true4、 findIndex:此方法返回滿足提供的測試功能的數(shù)組中第一個元素的索引。否則,它返回-1,表明沒有任何元素通過測試。
let testindex2 = users.findIndex(val => val.id > 1); //35、 find:此方法返回提供的數(shù)組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則返回undefined。
let testfind2 = users.find(el => (el.id > 2)); //{"id":3,"name":"sara"}6、filter:此方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
let testfilter2 = users.filter(val=> val.id>3);7、map:此方法創(chuàng)建一個新數(shù)組,其中填充了對調(diào)用數(shù)組中每個元素調(diào)用提供的函數(shù)的結(jié)果。
let val2 = []; users.map(item => { if(item.id >= 3) val2.push(item); });5、對數(shù)組項排序
可以使用sort方法對數(shù)組進(jìn)行排序。
該sort()方法對數(shù)組中的元素進(jìn)行適當(dāng)排序,然后返回排序后的數(shù)組。默認(rèn)的排序順序是升序,建立在將元素轉(zhuǎn)換為字符串,然后比較其UTF-16代碼單元值的序列的基礎(chǔ)上。
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]6、對具有特定屬性的對象數(shù)組進(jìn)行排序
這些是可以使用對象的特定屬性對對象數(shù)組進(jìn)行排序的方法。
1、簡單排序:此方法對數(shù)組中的元素進(jìn)行適當(dāng)排序,并返回排序后的數(shù)組。
let data = [{id: "3",city: "toronto",state: "TR",zip: "75201",price: "123451"},{id: "1",city: "anand",state: "AN",zip: "94210",price: "345678"},{id: "5",city: "sudbury",state: "SB",zip: "00110",price: "789045"} ]; let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id)));console.log("sort test 2 ", sorttest2); //output {"id": "1","city": "anand","state": "AN","zip": "94210","price": "345678" }, {"id": "3","city": "toronto","state": "TR","zip": "75201","price": "123451" }, {"id": "5","city": "sudbury","state": "SB","zip": "00110","price": "789045" }]2、localCompare:此方法返回一個數(shù)字,該數(shù)字指示參考字符串是按排序順序位于給定字符串之前,之后還是與之相同。
let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id))); //output [{"id": "1","city": "anand","state": "AN","zip": "94210","price": "345678" }, {"id": "3","city": "toronto","state": "TR","zip": "75201","price": "123451" }, {"id": "5","city": "sudbury","state": "SB","zip": "00110","price": "789045" }]3、用多個字段排序
該parseInt()函數(shù)解析一個字符串參數(shù),并返回一個指定基數(shù)的整數(shù)(數(shù)學(xué)數(shù)字系統(tǒng)中的基數(shù))。
let sorttest4 = data.sort(function(left, right) {var city_order = left.city.localeCompare(right.city);var price_order = parseInt(left.price) - parseInt(right.price);return city_order || -price_order; }); //output [{"id": "1","city": "anand","state": "AN","zip": "94210","price": "345678" }, {"id": "5","city": "sudbury","state": "SB","zip": "00110","price": "789045" }, {"id": "3","city": "toronto","state": "TR","zip": "75201","price": "123451" }]4、 Lodash _sortBy:創(chuàng)建一個元素數(shù)組,并按照在每個迭代中運行集合中每個元素的結(jié)果,以升序排序。
let sorttest6 = _.sortBy(data, ["id", "city"]); //output [{"id": "1","city": "anand","state": "AN","zip": "94210","price": "345678" }, {"id": "3","city": "toronto","state": "TR","zip": "75201","price": "123451" }, {"id": "5","city": "sudbury","state": "SB","zip": "00110","price": "789045" }]7、對日期數(shù)組進(jìn)行排序
1、使用sort
let isDescending = false; //set to true for Descending let dates = ["1/7/2021", "1/6/2021", "8/18/2020", "8/6/2020"]; let sorteddates = dates.sort((a, b) => isDescending ? new Date(b).getTime() - new Date(a).getTime() : new Date(a).getTime() - new Date(b).getTime()); console.log(sorteddates); //["8/6/2020", "8/18/2020", "1/6/2021", "1/7/2021"]2、使用Lodash
let arr = [{name: "test1",date: "1/7/2021"},{name: "test2",date: "1/6/2021"},{name: "test3",date: "1/5/2020"} ]; arr = _.sortBy(arr, function(dateObj) {return new Date(dateObj.date); }); console.log("sort date", arr); //[{"name":"test3","date":"1/5/2020"},{"name":"test2","date":"1/6/2021"},{"name":"test1","date":"1/7/2021"}]3、使用Lodash(按月和年排序)
let yearAndMonth = [{ "year": 2016, "month": "FEBRUARY" },{ "year": 2015, "month": "MARCH" },{ "year": 2021, "month": "JANUARY" },{ "year": 2021, "month": "FEBRUARY" } ] let value= _.sortBy(yearAndMonth, a => new Date(1 + a.month + a.year)); console.log('Sorted Result: ', value); //[{"year":2015,"month":"MARCH"},{"year":2016,"month":"FEBRUARY"},{"year":2021,"month":"JANUARY"},{"year":2021,"month":"FEBRUARY"}]8、從陣列中刪除一個項目
1、 pop:此方法從數(shù)組中刪除最后一個元素并返回該元素。此方法更改數(shù)組的長度。
let arraypoptest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];let testpop = arraypoptest.pop(); console.log("array pop", testpop,"-", arraypoptest); //10 - [2, 1, 2, 5, 6, 7, 8, 9, 9];2、shift:此方法從數(shù)組中刪除第一個元素并返回該刪除的元素。此方法更改數(shù)組的長度。
let arrayshifttest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let testshift = arrayshifttest.shift(); console.log("array shift", testshift,"-", arrayshifttest); //2 - [1, 2, 5, 6, 7, 8, 9, 9, 10]3、 slice:此方法將數(shù)組的一部分的淺表副本返回到一個新的數(shù)組對象中,該對象選自startto end(end不包括),其中startandend表示該數(shù)組中各項的索引。原始數(shù)組將不會被修改。
let arrayslicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let testslice = arrayslicetest.slice(0, 3); console.log("array slice", testslice, arrayslicetest); //not changed original array //[2, 1, 2] - [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]4、 splice:此方法通過刪除或替換現(xiàn)有元素和/或在適當(dāng)位置添加新元素來更改數(shù)組的內(nèi)容。
let arraysplicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let testsplice = arrayslicetest.splice(0, 3); //[2, 1, 2]5、 filter:此方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
數(shù)組:
let testarr = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let testarr2 = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let filtered = testarr.filter(function(value, index, arr) {return value > 5; }); let filtered2 = testarr2.filter(item => item !== 2); console.log("filter example 1", filtered); //[6, 7, 8, 9, 9, 10] console.log("filter example 2", filtered2); //[1, 5, 6, 7, 8, 9, 9, 10]過濾并去除多個值:
let forDeletion = [2, 3, 5]; let mularr = [1, 2, 3, 4, 5, 3]; mularr = mularr.filter(item => !forDeletion.includes(item)); console.log("multiple value deletion with filter", mularr); //[1, 4]6、delete運算符: JavaScript delete 從對象中刪除屬性;如果不再保存對相同屬性的引用,則最終將自動釋放該引用。
let ar = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; delete ar[4]; // delete element with index 4 console.log(ar); //[2, 1, 2, 5, undefined, 7, 8, 9, 9, 10]7、 lodash刪除:_remove刪除從所有元素array的是predicate返回truthy對于和返回被刪除的元素的數(shù)組。
let arrlodashtest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]; let evens = _.remove(arrlodashtest, function(n) {return n % 2 == 0; }); console.log("lodash remove array", arrlodashtest); //[1, 5, 7, 9, 9]9、從對象數(shù)組中刪除一個項目
1、 pop:此方法從數(shù)組中刪除最后一個元素并返回該元素。此方法更改數(shù)組的長度。
let users1 = [{id: 1,name: "ted" }, {id: 2,name: "mike" }, {id: 3,name: "bob" }, {id: 4,name: "sara" }]; let testpop1 = users1.pop(); console.log("array of objects pop",JSON.stringify(testpop1),"-"JSON.stringify(users1) ); //{"id":4,"name":"sara"} - [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]2、shift:此方法從數(shù)組中刪除第一個元素并返回該刪除的元素。此方法更改數(shù)組的長度。
let users2 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" } ]; let testshift1 = users2.shift(); console.log("array of objects shift", JSON.stringify(testshift1),"-", JSON.stringify(users2)); //{"id":1,"name":"ted"} - [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]3、 slice:此方法將數(shù)組的一部分的淺表副本返回到一個新的數(shù)組對象中,該對象選自startto end(不包括end),其中startandend表示該數(shù)組中各項的索引。原始數(shù)組將不會被修改。
let users3 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" } ]; let testslice1 = users3.slice(0, 3); console.log("array of objects slice", JSON.stringify(testslice1)); //not changed original array //[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]4、splice:此方法通過刪除或替換現(xiàn)有元素和/,或者在適當(dāng)位置添加新元素來更改數(shù)組的內(nèi)容。
let users4 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" } ]; let testspice1 = users3.splice(0, 3); console.log("array of objects splice", JSON.stringify(testsplice)); //[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]5、filter:此方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
let users7 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" } ]; let filterObj = users7.filter(item => item.id !== 2); console.log("filter example array of objects", filterObj); //[{"id":1,"name":"ted"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]6、lodash刪除:_remove刪除從所有元素array的是predicate返回truthy對于和返回被刪除的元素的數(shù)組。
let users8 = [ { id: 1, name: "ted" }, { id: 2, name: "mike" }, { id: 3, name: "bob" }, { id: 4, name: "sara" } ]; let evensObj = _.remove(users8, function(n) {return n.id % 2 == 0; }); console.log("lodash remove array of object", JSON.stringify(evensObj)); //[{"id":2,"name":"mike"},{"id":4,"name":"sara"}]10、從數(shù)組中給定的字符串中查找字符數(shù)
1、字符串匹配方法
該match()方法檢索將字符串與正則表達(dá)式匹配的結(jié)果。
const test1 = ("atit patel".match(/a/g)||[]).length console.log(test1); //22、字符串拆分方法
該split()方法將a String分為子字符串的有序列表,然后將這些子字符串放入數(shù)組中,然后返回該數(shù)組。
const test2 ="atit patel".split("a").length-1 console.log(test2); //23、indexOf方法
該indexOf()方法返回String第一次出現(xiàn)指定值的調(diào)用對象內(nèi)的索引,從開始搜索fromIndex。如果找不到該值,則返回-1。
let stringsearch = "a" ,str = "atit patel"; for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) ); console.log(count); //24、filter方法
該filter()方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
const mainStr = 'atit patel'; const test3 = [...mainStr].filter(l => l === 'a').length; console.log(test3); //25、reduce方法
該reduce()方法在數(shù)組的每個元素上執(zhí)行reducer函數(shù)(由你提供),從而產(chǎn)生單個輸出值。
const mainStr1 = 'atit patel'; const test4 = [...mainStr1].reduce((a, c) => c === 'a' ? ++a : a, 0); console.log(test4); //211、從數(shù)組中給定的字符串中查找每個字符的出現(xiàn)次數(shù)
1、我們可以添加reduce方法,該方法可以在迭代后返回對象
let s = 'atit patel'; let test5 = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {}); console.log(test5); //{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}2、與具有“或”運算符的方法6相同
let test6 = [...s].reduce((res, char) => (res[char] = (res[char] || 0) + 1, res), {}) console.log(test6);//{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}12、重命名對象數(shù)組中的對象屬性
1、使用Map:此方法創(chuàng)建一個新數(shù)組,其中填充了對調(diào)用數(shù)組中每個元素調(diào)用提供的函數(shù)的結(jié)果。
let countries = [ { id: 1, name: "india" }, { id: 2, name: "canada" }, { id: 3, name: "america" } ]; const transformed = countries.map(({ id, name }) => ({ label: id, value: name })); console.log("1", JSON.stringify(transformed));[{"label":1,"value":"india"},{"label":2,"value":"canada"},{"label":3,"value":"america"}]2、使用帶有參數(shù)的映射
const transformed2 = countries.map(({ id: label, name: value }) => ({ label, value })); console.log("2", JSON.stringify(transformed2)); [{"label":1,"value":"india"},{"label":2,"value":"canada"},{"label":3,"value":"america"}]3、使用lodash:_.mapKeys方法創(chuàng)建一個對象,該對象具有與和相同的值,該對象object和密鑰通過運行objectthru的每個自己的可枚舉字符串鍵控屬性生成iteratee。
const test1= _.mapKeys({ a: 1, b: 2 }, function(value, key) { return key + value; }); console.log("3",test1); //{a1: 1, b2: 2}如果我們想重命名對象鍵怎么辦?讓我們來看看解決方案。
4、將lodash用于值的對象
var users = { 'atit': { 'user': 'atit', 'age': 40 }, 'mahesh': { 'user': 'mahesh', 'age': 15 } }; const test2 = _.mapValues(users, function(o) { return o.age; }); console.log("4",test2); //{atit: 40, mahesh: 15} //shorthand const test3 =_.mapValues(users, 'age'); console.log("5",test3); //{atit: 40, mahesh: 15}5、使用對象解構(gòu):該解構(gòu)賦值語法是JavaScript表達(dá)式,使得它可以從陣列解壓縮的值,或從屬性的對象,為不同的變量。
const rename = (({id: a_b_c, ...rest}) => ({a_b_c, ...rest})) console.log(rename({id: 1, val: 2})) //{a_b_c: 1, val: 2}13、如何合并兩個數(shù)組并創(chuàng)建一個新數(shù)組?
這可以簡單地通過使用擴(kuò)展運算符來實現(xiàn)。
var arr1 = ['a', 'b', 'c'] var arr2 = ['d', 'e'] var merged = [...arr1, ...arr2] console.log(merged)14、一個數(shù)字?jǐn)?shù)組的總和
1、reduce可用于遍歷數(shù)組,將當(dāng)前元素值添加到先前元素值的總和中。
console.log([1, 2, 3, 4].reduce((a, b) => a + b, 0) ) console.log([].reduce((a, b) => a + b, 0) )//102、使用Lodash
array = [1, 2, 3, 4]; sum = _.sum(array); // sum == 1015、比較兩個對象數(shù)組,刪除重復(fù)項,根據(jù)屬性合并對象
我們確實需要比較兩個不同的對象數(shù)組,并且如果兩個對象匹配特定的屬性值,則希望合并這兩個對象,可以使用filter方法來實現(xiàn)。
該filter()方法創(chuàng)建一個新數(shù)組,其中所有元素都通過了由提供的功能實現(xiàn)的測試。
讓我們創(chuàng)建測試數(shù)據(jù)。
let array1 = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 } ]; let array2 = [ { id: "53", active: "a", value: 10 }, { id: "51", active: "a", value: 11 }, { id: "52", active: "a", value: 13 } ];讓我們創(chuàng)建函數(shù)。
let res = array2.filter(val =>array1.some(({value}) => (val.value as any) === (value as any)) ); console.log("1", JSON.stringify(res)); //[{"id":"53","active":"a","value":10},{"id":"51","active":"a","value":11}]16、比較兩個對象數(shù)組,合并和更新值(假設(shè)數(shù)組3,4共享相同的ID)
有時我們確實會獲得要求,以將兩個不同的屬性與新的屬性值合并。我們可以使用地圖創(chuàng)建一組新的對象數(shù)組,并且可以使用find方法在更新新值之前匹配特定屬性。
該map()方法創(chuàng)建一個新數(shù)組,其中填充了在調(diào)用數(shù)組中每個元素上調(diào)用提供的函數(shù)的結(jié)果。
該find()方法返回提供的數(shù)組中滿足提供的測試功能的第一個元素的值。如果沒有值滿足測試功能,則返回undefined。(來源:MDN)
讓我們創(chuàng)建測試數(shù)據(jù)。
let array3 = [ { id: "50", active: "a", value: 12 }, { id: "51", active: "a", value: 15 } ]; let array4 = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 }, { id: "52", active: "a", value: 13 } ];讓我們創(chuàng)建函數(shù)。
let arr = []; array3.map(id =>arr.push({id: id.id,newValue: array4.find(o => o.id === id.id).value + 2}) ); console.log("2", JSON.stringify(arr)); //[{"id":"50","newValue":12},{"id":"51","newValue":13}]17、比較對象數(shù)組并找到唯一的對象
如果我們要比較兩個對象數(shù)組并檢查其中哪些是唯一對象,則可以使用filter來實現(xiàn)這些功能。
讓我們創(chuàng)建測試數(shù)據(jù)。
const array5 = [ { id: "50", active: "a", value: 12 }, { id: "51", active: "a", value: 15 } ]; const array6 = [ { id: "50", active: "a", value: 12 }, { id: "51", active: "a", value: 15 }, { id: "52", active: "a", value: 13 } ];讓我們創(chuàng)建函數(shù)
const ids = array5.map(e => e.id); let filtered = array6.filter(e => ids.includes(e.id)); console.log("3", JSON.stringify(filtered)); //[{"id":"50","active":"a","value":12},{"id":"51","active":"a","value":15}]18、根據(jù)匹配的值比較和更新屬性
當(dāng)我們要比較兩個對象數(shù)組并根據(jù)匹配的值更新特定的屬性時,可以使用這些函數(shù)。
讓我們創(chuàng)建測試數(shù)據(jù)
const array7 = [ { id: "50", active: "a", value: 12 }, { id: "51", active: "a", value: 15 } ]; const array8 = [{ id: "50", active: "a", value: 12 }];讓我們創(chuàng)建函數(shù)
const idSet = new Set(array8.map(o => o.id)); const res1 = array7.map(o => ({ ...o, value: idSet.has(o.id) ? "0" : o.value })); console.log("4", JSON.stringify(res1)); //[{"id":"50","active":"a","value":"0"},{"id":"51","active":"a","value":15}19、比較兩個數(shù)組對象并獲得差異
當(dāng)我們要比較兩個不同的對象數(shù)組并得到它們之間的差異時,可以使用這些函數(shù)。
讓我們創(chuàng)建測試數(shù)據(jù)
let a = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 } ]; let b = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 }, { id: "52", active: "a", value: 13 } ];讓我們創(chuàng)建函數(shù)
let valuesArray1 = a.reduce(function(a, c) {a[c.value] = c.value;return a; }, {}); let valuesArray2 = b.reduce(function(a, c) {a[c.value] = c.value;return a; }, {}); var result = a.filter(function(c) {return !valuesArray2[c.value];}).concat(b.filter(function(c) {return !valuesArray1[c.value];})); console.log("5", result); //[{"id":"52","active":"a","value":13}] //shorthand let ab = b.filter(o => !a.find(o2 => o.id === o2.id)); console.log("6", ab);20、比較對象的兩個數(shù)組合并并刪除重復(fù)項
如果我們有要求比較兩個對象數(shù)組并從它們中刪除重復(fù)項并合并兩個數(shù)組,則可以使用此方法。
讓我們創(chuàng)建測試數(shù)據(jù)
let arr1 = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 } ]; let arr2 = [ { id: "50", active: "a", value: 10 }, { id: "51", active: "a", value: 11 }, { id: "52", active: "a", value: 13 } ];讓我們創(chuàng)建函數(shù)
const arr1IDs = new Set(arr1.map(({ id }) => id)); const combined = [...arr1, ...arr2.filter(({ id }) => !arr1IDs.has(id))]; console.log(JSON.stringify(combined)); //[{"id":"50","active":"a","value":10},{"id":"51","active":"a","value":11},{"id":"52","active":"a","value":13}]使用lodash
Lodash支持_differenceBy和 _differenceWith查找兩個數(shù)組之間差異的方法。
let lodashtest1 = [{ id: "50" }, { id: "51" }]; let lodashtest2 = [{ id: "50" }, { id: "51" }, { id: "52" }]; let lodashresult = _.differenceBy(lodashtest2, lodashtest1, "id"); console.log("7", JSON.stringify(lodashresult)); //[{"id":"52"}] let dif = _.differenceWith(lodashtest2, lodashtest1, _.isEqual); console.log("8",JSON.stringify(dif)); //[{"id":"52"}]21、比較對象并找到唯一值
當(dāng)我們處理嵌套對象時,有時很難弄清楚我們?nèi)绾蔚捅容^兩個嵌套對象并在其中獲得一些唯一的對象。我們可以使用Object.keys和Object.values方法進(jìn)行迭代。
讓我們創(chuàng)建測試數(shù)據(jù)
let obj1 = { val1: "test", stream: { prop1: false, prop2: true } }; let obj2 = { val1: "test", stream: { prop1: true, prop2: true } }; interface Data { stream: { [key: string]: boolean }; }讓我們創(chuàng)建測試數(shù)據(jù)
function objFilter(objA: Data, objB: Data): Data { let out: Data = { stream: {} }; Object.keys(objA.stream).filter((value, idx) => Object.values(objA.stream)[idx] === Object.values(objB.stream)[idx] ? (out.stream[value] = Object.values(objA.stream)[idx]) : false ); return out; } console.log(JSON.stringify(objFilter(obj1, obj2))); //prop2 //{"stream":{"prop2":true}}22、如何處理循環(huán)內(nèi)的多個服務(wù)調(diào)用
1、如果我們不想等待所有服務(wù)呼叫完成
let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]; async function getDetails(values) {for (const data of values) {const result = await axios.get(`serviceURL/${data.id}`);const newData = result.data;this.updateDetails(newData);console.log(this.response);} } function updateDetails(data) {this.response.push(data); } getDetails(data); //call service to get data2、如果我們要等到所有服務(wù)呼叫完成
我們可以用promise.all來等到所有的諾言都解決了。
該Promise.all()方法將一個可迭代的Promise作為輸入,并返回一個Promise解析為輸入Promise結(jié)果數(shù)組的單個對象。
let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]; async function getDetails(values) {const dataPromises = values.map(entry => {return axios.get(`serviceURL/${entry.id}`);}); const resultData = await Promise.all(dataPromises); resultData.forEach((res: any) => {this.updateDetails(res.data);});console.log(this.response); } function updateDetails(data) {this.response.push(data); } getDetails(data); //call service to get data總結(jié)
以上是生活随笔為你收集整理的JavaScript编程知识的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript单行代码
- 下一篇: CSS3运算 calc()函数是怎么实现