Home > Enterprise >  JavaScript: Working with Two Arrays of Objects
JavaScript: Working with Two Arrays of Objects

Time:10-18

//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 },
]

I want to create a function with arr1 & arr2 as arguments.

Where arr1.address == arr2.address => take arr2.value => Put in arr1.value

Sum the values by addKey then add to 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 },
]

CodePudding user response:

Try this once:

//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);

CodePudding user response:

You can use map and reduce to do it

let 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 },
]

let arr2 = [
    {address: '11', value: 5, total: 0 },
    {address: '12', value: 10, total: 0 },
]

arr1 = arr1.map(a => {
  a.value = arr2.find(i => a.address == i.address)?.value || 0
  return a
})
arr2 = arr2.map(a => {
   a.total = arr1.filter(i => i.address == a.address).reduce((a,v) => a   v.value,0)
   return a
})

console.log(arr1)
console.log(arr2)

  • Related