当我尝试使用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"
}
是数据量问题还是?
.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
});
}
});
试试这个代码。
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
}
}
});