Search code examples
javascriptnode.jsarraysmergearray-map

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


I keep having issues when trying to merge data using map() and find() to merge two arrays of objects, often receiving something along the lines of TypeError: Cannot read property 'customSku' of null

I'm selecting the object keys correctly, so I'm wondering if there is something inherently wrong with the way I am trying to do this as sometimes it works, sometimes it doesn't.

My latest attempt looks like:

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

With data like so:

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

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

Is it an issue with the amount of data or?


Solution

  • Try this code.

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