Conditional copying properties and values from one array of objects to another

Viewed 111

Got two arrays of objects and my goal is to check if the value under property id from array1 matches the value under the property categoryId of array2. When find a match want to add the missing property amount to the relevant member of array1 or create a new array containing all the properties and values I need - id, name, amount

Here are the two arrays:

const array1 = [{
  id: 8,
  name: 'Online Shopping',
},
{
  id: 12,
  name: 'Subscriptions',
},
{
 id: 5,
  name: 'Patreon donations',
}]

and

const array2 = [
{
  expence: {
    amount: -66.66,
  },
  categoryId: 5,
},
{
  expence: {
    amount: 100018.85,
  },
  categoryId: 0,
},
{
  expence: {
    amount: -43340.9,
  },
  categoryId: 12,
},]

Tried to combine different approaches from answers to similar but simpler cases already posted in the community but didn't managed to make them work in my case.

1 Answers

Loop through each item in array1, then loop through each item in array2 inside the loop and check whether the categoryId is equal to the id.

const array1 = [{
    id: 8,
    name: 'Online Shopping',
  },
  {
    id: 12,
    name: 'Subscriptions',
  },
  {
    id: 5,
    name: 'Patreon donations',
  }
]
const array2 = [{
    expence: {
      amount: -66.66,
    },
    categoryId: 5,
  },
  {
    expence: {
      amount: 100018.85,
    },
    categoryId: 0,
  },
  {
    expence: {
      amount: -43340.9,
    },
    categoryId: 12,
  },
]

array1.forEach((e) => {
  array2.forEach((f) => {
    if (f.categoryId == e.id) {
      e.amount = f.expence.amount;
    }
  })
})
console.log(array1);

You can also make use of Array.filter to find the item where the categoryId is equal to the id:

const array1 = [{
    id: 8,
    name: 'Online Shopping',
  },
  {
    id: 12,
    name: 'Subscriptions',
  },
  {
    id: 5,
    name: 'Patreon donations',
  }
]
const array2 = [{
    expence: {
      amount: -66.66,
    },
    categoryId: 5,
  },
  {
    expence: {
      amount: 100018.85,
    },
    categoryId: 0,
  },
  {
    expence: {
      amount: -43340.9,
    },
    categoryId: 12,
  },
]

array1.forEach((e) => {
  var arr = array2.filter(f => f.categoryId == e.id);
  if(arr.length > 0) e.amount = arr[0].expence.amount;
})
console.log(array1);

Related