Почему не удается выполнить слияние? map () find () [javascript] - PullRequest
0 голосов
/ 04 августа 2020

У меня все еще возникают проблемы при попытке объединить данные с помощью 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"
  }

Это проблема с объемом данных или?

Ответы [ 2 ]

1 голос
/ 04 августа 2020

.map ожидает, что что-то будет возвращено всегда. Используйте forEach до l oop и выполните условное слияние

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 
    });
  }
});
1 голос
/ 04 августа 2020

Попробуйте этот код.

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 
    }
  }
});
...