为什么我的合并失败?地图()查找()[javascript]

Why does my Merge fail? map() find() [javascript]

我在尝试使用 map() 和 find() 合并数据以合并两个对象数组时一直遇到问题,经常收到类似 TypeError: Cannot read property 'customSku' of null

的内容

我正确地选择了对象键,所以我想知道我尝试执行此操作的方式是否存在固有错误,因为它有时有效,有时却无效。

我最近的尝试是这样的:

const fs = require('fs')
const binLocations = require("../data/json/locations.json");
const opsuiteItems = require('../data/json/items.json')

const merged = binLocations.map((item) => {
  itm = opsuiteItems.find((itm) => itm.customSku === item.customSku)
  if (itm) {
    return {
      itemID: item.itemID,
      customSku: itm.customSku,
      defaultCost: itm.vendorCost,
      tag: item.binLocation 
    }
  }
})

数据如下:

//opsuiteItems
{
    "active": true,
    "customSku": "H2442",
    "vendorCost": "19",
  }

// binLocations
{
    "itemID": "2840",
    "customSku": "H2442",
    "binLocation": "G"
  }

是数据量的问题还是?

试试这个代码。

const merged = binLocations.filter((item) => {
  return item != null && opsuiteItems.findIndex((opItem) => opItem.customSku === item.customSku) >= 0;
}).map((item) => {
  const itm = opsuiteItems.find((itm) => itm.customSku === item.customSku)
  if (itm) {
    return {
      itemID: item.itemID,
      customSku: itm.customSku,
      defaultCost: itm.vendorCost,
      tag: item.binLocation 
    }
  }
});

.map 期望总是返回一些东西。使用forEach循环并进行条件合并

const merged = [];

binLocations.forEach(item => {
  const match = item && opsuiteItems.find(el => el.customSku === item.customSku);

  if (match) {
    merged.push({
      itemID: item.itemID,
      customSku: item.customSku,
      defaultCost: match.vendorCost,
      tag: item.binLocation 
    });
  }
});