我有一個表已經填充了來自 API 的資料集。對于演示,假設我已經在從 API 獲取的表上添加了 2 行。現在,我編輯了第二行還添加了另一行。所以我想要實作的是我想要獲得一個新的物件陣列,其中包含我剛剛編輯的行和我剛剛添加的行。
以下是我擁有的帶有虛擬資料集的 2 個陣列。
第一個陣列:
[
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 8, end: 36 }, point: 49 },
]
第二個陣列:
[
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 },
{ id: null, count: { start: 123, end: 2135 }, point: 323 },
]
請注意,我編輯了Second Array. 第二個陣列中的第三行沒有用戶 ID,因為userId發布后將從服務器回傳
預期輸出:
[
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 },
{ id: null, count: { start: 123, end: 2135 }, point: 323 },
]
我試過lodash _.differencWith/_.intersectWith但使用它的輸出如下
[
{ id: null, count: { start: 123, end: 2135 }, point: 323 },
]
只回傳表上新添加的行,但忽略了我也更改了第二行的值。
注意:該表只有 3 列,所有列都可以編輯。coun: { start, end}和point
uj5u.com熱心網友回復:
您可以使用_.differenceWith(https://lodash.com/docs/4.17.15#differenceWith)
const first=[
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 8, end: 36 }, point: 49 },
]
const second=[
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 },
{ id: null, count: { start: 123, end: 2135 }, point: 323 },
]
let result=_.differenceWith(second, first, _.isEqual)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
_.differenceWith:
這個方法很像,_.difference除了它接受比較器,它被呼叫來比較陣列的元素和值。結果值的順序和參考由第一個陣列決定。使用兩個引數呼叫比較器:(arrVal, othVal).
uj5u.com熱心網友回復:
const a = [
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 8, end: 36 }, point: 49 },
]
const b = [
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 },
{ id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 },
{ id: null, count: { start: 123, end: 2135 }, point: 323 },
];
result = _.differenceWith(b, a, _.isEqual)
console.log(result); // your excpected result.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379558.html
標籤:javascript 数组 目的 洛达什
