我有 2 個物件。
const obj1 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}];
const obj2 = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];
我想把它們合二為一,但不重復。結果應該是 obj3 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];
const obj3 = obj1.map((item) => obj2.filter((i) => i !== item));
不管用。
uj5u.com熱心網友回復:
問題是你正在映射一個陣列,所以基本上你filter每次都會這樣做obj1.length。
就 而言filter,過濾器將洗掉所有相同的專案obj1,您只會得到不重復的專案obj2,您可以將它們分組。
我建議的另一個好的解決方案是concat兩個陣列和filter它。
const obj1 = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}];
const obj2 = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 8, b: 3}, {a: 7, b: 3}];
let obj3 = obj1.concat(obj2)
let obj4=obj3.filter((item,index) => obj3.indexOf(item) === index)
console.log(obj4)
uj5u.com熱心網友回復:
您總是可以嘗試回圈遍歷第一個條目并回圈遍歷每個條目的第二個條目,檢查是否有重復。
uj5u.com熱心網友回復:
使用 lodash libray 來處理陣列操作很方便,就像您要詢問的那樣:https ://lodash.com/docs/4.17.15#union
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
將 lodash 庫添加到代碼中很容易。您可以在此處下載并保存 lodash.js 檔案:https ://lodash.com/ ,或者僅使用 CDN 中的 url 并包含在您的其他腳本/腳本標簽中:https : //cdnjs.com/libraries/lodash .js
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420319.html
標籤:
下一篇:組件在狀態更改未發生時重新渲染
