//Before
export const arr1 = [
{ addKey: '11', address: '12', value: 0 },
{ addKey: '11', address: '12', value: 0 },
{ addKey: '12', address: '11', value: 0 },
{ addKey: '12', address: '11', value: 0 },
]
export const arr2 = [
{address: '11', value: 5, total: 0 },
{address: '12', value: 10, total: 0 },
]
我想創建一個以 arr1 & arr2 作為引數的函式。
其中 arr1.address == arr2.address => 取 arr2.value => 放入 arr1.value
通過 addKey 對值求和,然后添加到 arr2.total
//After
export const arr1After = [
{ addKey: '11', address: '12', value: 10 },
{ addKey: '11', address: '12', value: 10 },
{ addKey: '12', address: '11', value: 5 },
{ addKey: '12', address: '11', value: 5 },
]
export const arr2After = [
{address: '11', value: 5, total: 20 },
{address: '12', value: 10, total: 10 },
]
uj5u.com熱心網友回復:
試試這個:
//using for loop
const changeValue = (arr1, arr2) => {
for (let i = 0; i < arr1.length; i ) {
for (let j = 0; j < arr2.length; j ) {
if (arr1[i].address === arr2[j].address) {
arr1[i].value = arr2[j].value;
arr2[j].total = arr2[j].value;
}
}
}
console.log(arr1, arr2);
};
//using foreach loop
const changeValue = (arr1, arr2) => {
arr1.forEach((arr1Elem) => {
arr2.forEach((arr2Elem) => {
if (arr1Elem.address === arr2Elem.address) {
arr1Elem.value = arr2Elem.value;
arr2Elem.total = arr2Elem.value;
}
});
});
console.log(arr1, arr2);
};
changeValue(arr1, arr2);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517339.html
上一篇:React鉤子/異步行為的問題