为什么这个forEach()var无法解析?

时间:2020-02-05 01:50:06

标签: javascript

我有一些代码,

  1. 从对象的js数组中获取所有ID
  2. 将这些ID的不同列表创建到新变量中
  3. 针对ID的唯一列表进行forEach以便进行1-by-1处理
let commodityIds = supplierPricingInfo.map(x => x.CommodityId);
let distinctCommodityIds = [...new Set(commodityIds)];
distinctCommodityIds.forEach(x => {
    sapCommodityRows = supplierPricingInfo.filter(x => x.CommodityId === x);
    debugger;
});

当我的代码到达上面的调试器断点时,手表中显示的forEach x值为2,但是vendorPricingInfo没有返回匹配的行(尽管应该有)。但是,如果我将x变量值硬编码为2,则匹配的行将从providerPricingInfo返回。这很奇怪。我认为我之前从未见过这样的问题。你知道根本原因是什么吗?

2 个答案:

答案 0 :(得分:1)

我认为您的x是混乱的。尝试将外部x替换为id,如下所示:

distinctCommodityIds.forEach(id => {
  sapCommodityRows = supplierPricingInfo.filter(x => x.CommodityId === id);
  debugger;
});

答案 1 :(得分:0)

您可以检查一下吗,这里我们从数组中获得唯一的CommodityId。

let items = [
  { id: 1, CommodityId: 1, name: 'Alex' },
  { id: 2, CommodityId: 2, name: 'John' },
  { id: 3, CommodityId: 1, name: 'Jane' },
  { id: 4, CommodityId: 3, name: 'Doe' },
  { id: 5, CommodityId: 2, name: 'Peter' }
];

const unique = [...new Set(items.map(item => item.CommodityId))];
console.log(unique)