有条件地将属性和值从一个对象数组复制到另一个对象数组

问题描述

有两个对象数组,我的目标是检查 array1 中的属性 id 下的值是否与属性 categoryId 下的值匹配array2。当找到匹配项时想要将缺失的属性 amount 添加array1 的相关成员或创建一个包含我需要的所有属性和值的新数组 - 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中的每一项,然后在循环内循环遍历array2中的每一项并检查categoryId是否等于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);

您还可以使用 Array.filter 来查找 categoryId 等于 id 的项目:

const array1 = [{
    id: 8,]

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