【问题标题】:Conditional copying properties and values from one array of objects to another有条件地将属性和值从一个对象数组复制到另一个对象
【发布时间】:2021-07-14 17:03:15
【问题描述】:

有两个对象数组,我的目标是检查 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,
},]

试图结合不同的方法,从答案到社区中已经发布的类似但更简单的案例,但没有设法让它们在我的案例中起作用。

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    循环遍历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,
        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);

    【讨论】:

    • 非常感谢 Spectric,这两个示例都适用于我的情况。我想需要回到 JS 基础。干杯。
    猜你喜欢
    • 2022-12-04
    • 2016-12-21
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2016-09-20
    • 2014-12-08
    相关资源
    最近更新 更多