我有 2 個陣列,如果它們具有相同的兩個物件鍵,我想將它們組合起來。
如果未找到匹配項,則仍保留該物件,但值為 0。
輸入示例
withdrawal: [
{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
{
"id": "c3",
"withdrawalAmount": 33,
"user": "John"
}
]
deposit: [
{
"id": "a1",
"depositAmount": 123,
"user": "John"
},
{
"id": "c3",
"depositAmount": 44,
"user": "John"
},
]
預期產出
transactions: [
{
"id": "a1",
"depositAmount": 123,
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"depositAmount": 0,
"withdrawalAmount": 100,
"user": "Mike"
},
{
"id": "c3",
"depositAmount": 44,
"withdrawalAmount": 33
"user": "John"
},
]
這是我迄今為止嘗試過的函式,但由于兩個輸入陣列的長度不同,它不起作用。
function mergeArrayObjects(arr1, arr2) {
return arr1.map((item, i) => {
if (item.user === arr2[i].user) {
//merging two objects
return Object.assign({}, item, arr2[i])
}
})
}
uj5u.com熱心網友回復:
您可以通過處理提款和存款串列來達到您想要的結果,使用Array.reduce以id值作為鍵deposit和withdrawal金額作為值的物件;然后,您可以獲取該物件的值來創建transactions陣列:
const withdrawal = [{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
]
const deposit = [{
"id": "a1",
"depositAmount": 123,
"user": "John"
},
{
"id": "c3",
"depositAmount": 44,
"user": "John"
}
]
const transactions = Object.values(
withdrawal
.concat(deposit)
.reduce((c, { id, depositAmount, withdrawalAmount, ...rest }) => {
c[id] = c[id] || {}
depositAmount = c[id]['depositAmount'] || depositAmount || 0;
withdrawalAmount = c[id]['withdrawalAmount'] || withdrawalAmount || 0;
c[id] = ({ id, depositAmount, withdrawalAmount, ...rest });
return c;
},
{})
)
console.log(transactions)
.as-console-wrapper { max-height: 100% !important; top: 0 }
如果您想同時按idand進行分組user,您需要將結果物件鍵從兩個值中取出,并由一個不在其中任何一個中的字符連接(例如#,適用于您的資料):
const withdrawal = [{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
]
const deposit = [{
"id": "a2",
"depositAmount": 123,
"user": "John"
},
{
"id": "b2",
"depositAmount": 109,
"user": "Mike"
},
{
"id": "c3",
"depositAmount": 44,
"user": "John"
}
]
const transactions = Object.values(
withdrawal
.concat(deposit)
.reduce((c, { id, user, depositAmount, withdrawalAmount, ...rest }) => {
key = `${id}#${user}`
c[key] = c[key] || {}
depositAmount = c[key]['depositAmount'] || depositAmount || 0;
withdrawalAmount = c[key]['withdrawalAmount'] || withdrawalAmount || 0;
c[key] = ({ id, user, depositAmount, withdrawalAmount, ...rest });
return c;
},
{})
)
console.log(transactions)
.as-console-wrapper { max-height: 100% !important; top: 0 }
uj5u.com熱心網友回復:
下面介紹的是實作預期目標的一種可能方式。
代碼片段
// helper method to obtain all props
// from array-elt matching "id"
const getInfo = (ar, argId) => (
ar?.find(({ id }) => id === argId) ?? {}
);
// combine both arrays using "id"
const combineArrays = (ar1, ar2) => {
// first get unique ids combining both arrays
const uniqIds = [
...new Set(
[...ar1, ...ar2]
.map(({ id }) => id)
)
];
// now, for each unique id
// simply get relevant info from both
// arrays where element's match the "id"
return uniqIds.map(id => ({
id,
...getInfo(ar1, id),
...getInfo(ar2, id)
}));
};
const withdrawal = [{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
];
const deposit = [{
"id": "a1",
"depositAmount": 123,
"user": "John"
}];
// invoke the method and display the result
console.log(
'combined both arrays as below:\n',
combineArrays(withdrawal, deposit)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
解釋
添加到上述代碼段的行內注釋。
uj5u.com熱心網友回復:
在第一次迭代中僅合并公共物件,然后重新迭代兩個陣列并在最終陣列中只取未使用的專案。
class Transaction {
constructor(transaction) {
this.id = transaction.id;
this.depositAmount = transaction.depositAmount | 0;
this.withdrawAmount = transaction.withdrawalAmount | 0;
this.user = transaction.user;
}
}
let withdrawl = [
{
id: "a1",
withdrawalAmount: 300,
user: "John",
},
{
id: "b2",
withdrawalAmount: 100,
user: "Mike",
},
{
id: "c3",
withdrawalAmount: 33,
user: "John",
},
];
let deposit = [
{
id: "a1",
depositAmount: 123,
user: "John",
},
{
id: "c3",
depositAmount: 44,
user: "John",
},
];
let transactions = [];
// merge the common key of two array into one array
withdrawl.forEach((item1) => {
deposit.forEach((item2) => {
if (item1.id === item2.id) {
let combined = { ...item1, ...item2 };
let transaction = new Transaction(combined);
transactions.push(transaction);
// mark the item as used
// or set some flag to know
// the item is used in the array
item1.used = true;
item2.used = true;
}
})
})
// now take all the unused item from the both array
// and push them to the transactions array
withdrawl.forEach((item1) => {
if (!item1.used) {
let transaction = new Transaction(item1);
transactions.push(transaction);
}
});
deposit.forEach((item2) => {
if (!item2.used) {
let transaction = new Transaction(item2);
transactions.push(transaction);
}
});
console.log(transactions);
uj5u.com熱心網友回復:
const withdrawal = [{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
}
]
const deposit = [{
"id": "a1",
"depositAmount": 123,
"user": "John"
}, ]
const mergeArr = withdrawal.map(ele => {
let other = deposit.find(({id}) => id === ele.id)
return other ? {...ele, ...other} : {...ele, depositAmount : 0}
})
console.log(mergeArr)
uj5u.com熱心網友回復:
對于大型陣列,請使用 Nick 的方法(最終您將節省大量周期)
對于陣列中的少量專案,一個解決方案find()就足夠了:
const withdrawal= [
{
"id": "a1",
"withdrawalAmount": 300,
"user": "John"
},
{
"id": "b2",
"withdrawalAmount": 100,
"user": "Mike"
},
{
"id": "c3",
"withdrawalAmount": 33,
"user": "John"
}
]
const deposit= [
{
"id": "a1",
"depositAmount": 123,
"user": "John"
},
{
"id": "c3",
"depositAmount": 44,
"user": "John"
}
]
const transactions = withdrawal.map(item => ({"depositAmount": 0, ...item}));
deposit.forEach( item => {
const found = transactions.find(x => x.id === item.id);
if (found) {
Object.assign(found,item);
} else {
transactions.push(Object.assign(item,{"withdrawalAmount": 0}));
}
});
console.log(transactions)
注意:此代碼假定您想要兩個陣列的并集而不是交集
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483574.html
標籤:javascript 数组 打字稿 目的
上一篇:如何將java物件轉換為Json
