映射对象的嵌套数组

Mapping nested arrays of objects

提问人:dariusz 提问时间:5/24/2023 最后编辑:dariusz 更新时间:5/25/2023 访问量:15

问:

我有两个对象数组。

第一个是:

const accounts = [
  {
    "id": "dbcaf288-2b39-4b95-8ab3-42202ab15918",
    "nominalCode": "090",
    "name": "Business Current Account",
    "accountLinks": [
      "UUID1",
      "UUID2",
      "UUID3"
    ]
  },
  {
    "id": "a989e8c6-376c-43f0-8938-397d7831e216",
    "nominalCode": "091",
    "name": "Business Savings Account",
    "accountLinks": [
      "UUID4",
      "UUID5"
    ]
  },
  {
    "id": "e5d7612c-1671-47b4-b733-5db48363fcd0",
    "nominalCode": "630",
    "name": "Inventory",
    "accountLinks": []
  },
];

第二个:

const entities = [
  {
    "id": "UUID1",
    "name": "EUR Account",
  },
  {
    "id": "UUID2",
    "name": "USD Account",
  },
  {
    "id": "UUID3",
    "name": "Administration",
  },
  {
    "id": "UUID4",
    "name": "Office Supplies",
  },
  {
    "id": "UUID6",
    "name": "Vehicles",
  }
];

我试图得到的是基于帐户的数组,但如果 entities[i].id === accounts[i].accountLinks[i] 或空数组(如果比较为 false),则添加 dropdownAccounts 属性及其实体数组值。 因此,新数组将如下所示:

const rows = [
    {
      id: 'dbcaf288-2b39-4b95-8ab3-42202ab15918',
      nominalCode: '090',
      name: 'Business Current Account',
      accountLinks: [
        'UUID1',
        'UUID2',
        'UUID3',
      ],
      dropdownAccounts: [
        {
          id: 'UUID1',
          name: 'EUR Account',
        },
        {
          id: 'UUID2',
          name: 'USD Account',
        },
        {
          id: 'UUID3',
          name: 'Administration',
        },
      ],
    },
    {
      id: 'a989e8c6-376c-43f0-8938-397d7831e216',
      nominalCode: '091',
      name: 'Business Savings Account',
      accountLinks: [
        'UUID4',
        'UUID5',
      ],
      dropdownAccounts: [
        {
          id: 'UUID4',
          name: 'Office Supplies',
        },
        {
          id: 'UUID5',
          name: 'Vehicles',
        },
      ],
    },
    {
      id: 'e5d7612c-1671-47b4-b733-5db48363fcd0',
      nominalCode: '630',
      name: 'Inventory',
      accountLinks: [],
      dropdownAccounts: [],
    },
  ];

到目前为止,我的解决方案是:

const rows = accounts.map((account) => {
  return {...account, dropdownAccounts: entities.find(item=>item.id === account.code)}
})

但不幸的是,它给了我,我很遗憾,我并不感到惊讶,因为我知道我正在失去实体中的逻辑。dropdownAccounts: undefined

好的,我已经解决了:

const rows2 = accounts.map((account) => {
  return {
    ...account,
    dropdownAccounts: []
  };
});

rows2.forEach((row) => {
  row.accountLinks.forEach((link) => {
    entities.forEach((entity) => {
      if(entity.id === link) {
        row.dropdownAccounts.push(entity);
      }
    })
  })
})

但是,我对代码质量不满意。 知道如何让它更整洁吗?:)

嵌套的 Arrays 对象

评论


答: 暂无答案