1
\$\begingroup\$
I have created a tool to insert JSON objects with several rules:
  1. Read the product status, and then insert based on the status
  2. If there is no data in this status, then insert the object
  3. If there is data in the status, then check the Name. If the name already exists then just insert the product Id into the existing one
  4. If the name does not exist then just insert it as new object

The Incoming data

const incoming = [
  { productName: "Soda", productId: "TC-532", productStatus: "Passed" },
  { productName: "Soda", productId: "TC-535", productStatus: "Failed" },
  {
    productName: "Water",
    productId: "TC-3209",
    productStatus: "Passed",
  },
  {
    productName: "Bread",
    productId: "TC-3210",
    productStatus: "Passed",
  },
  {
    productName: "Salt",
    productId: "TC-1312",
    productStatus: "Failed",
  },
  {
    productName: "Salt",
    productId: "TC-6370",
    productStatus: "Failed",
  },
  {
    productName: "Bread",
    productId: "TC-3214",
    productStatus: "Passed",
  },
  {
    productName: "Water",
    productId: "TC-3222",
    productStatus: "Skipped",
  }
];

The target data

const storage = {
  Passed: [],
  Failed: [],
  Skipped: []
};

Based on the rule, my expectation result should become like this

{
  "Passed": [
    {
      "productName": "Soda",
      "productId": [
        "TC-532"
      ]
    },
    {
      "productName": "Water",
      "productId": [
        "TC-3209"
      ]
    },
    {
      "productName": "Bread",
      "productId": [
        "TC-3210",
        "TC-3214"
      ]
    }
  ],
  "Failed": [
    {
      "productName": "Soda",
      "productId": [
        "TC-535"
      ]
    },
    {
      "productName": "Salt",
      "productId": [
        "TC-1312",
        "TC-6370"
      ]
    }
  ],
  "Skipped": [
    {
      "productName": "Water",
      "productId": [
        "TC-3222"
      ]
    }
  ]
}

So far I've created the code, but I need your review is there any input that can improve my code. Perhaps redundant function or something else, thanks !

const incoming = [
  { productName: "Soda", productId: "TC-532", productStatus: "Passed" },
  { productName: "Soda", productId: "TC-535", productStatus: "Failed" },
  {
    productName: "Water",
    productId: "TC-3209",
    productStatus: "Passed",
  },
  {
    productName: "Bread",
    productId: "TC-3210",
    productStatus: "Passed",
  },
  {
    productName: "Salt",
    productId: "TC-1312",
    productStatus: "Failed",
  },
  {
    productName: "Salt",
    productId: "TC-6370",
    productStatus: "Failed",
  },
  {
    productName: "Bread",
    productId: "TC-3214",
    productStatus: "Passed",
  },
  {
    productName: "Water",
    productId: "TC-3222",
    productStatus: "Skipped",
  }
];

const storage = {
  Passed: [],
  Failed: [],
  Skipped: [],
};

const temp = {
  productName: "",
  productId: "",
};

for (const key in incoming) {
  let theStatus = incoming[key].productStatus;
  switch (theStatus) {
    case "Passed":
      var source = storage["Passed"];
      /* Check If the category already has the data or not */
      if (source.length > 0) {
        /* If yes, then insert the data */
        pushData(source, incoming[key]);
      } else {
        /* If no, then start to create new object */
        pushInitial("Passed", incoming[key]);
      }
      break;
    case "Failed":
      var source = storage["Failed"];
      if (source.length > 0) {
        pushData(source, incoming[key]);
      } else {
        pushInitial("Failed", incoming[key]);
      }
      break;
    case "Skipped":
    var source = storage["Skipped"];
    if (source.length > 0) {
        pushData(source, incoming[key]);
    } else {
        pushInitial("Skipped", incoming[key]);
    }
    break;
  }
}

console.log(JSON.stringify(storage, null, 2));

function pushInitial(productStatus, data) {
  let temp = {};
  temp.productName = data.productName;
  temp.productId = [data.productId];
  storage[productStatus].push(temp);
}

function pushData(current, incom) {
  let temp = {};
  let isFound = false;
  for (const key in current) {
    const sourceData = current[key].productName;
    const targetData = incom.productName;
    // Check if the product name in json array is already define or not
    if (checkAlreadyExist(sourceData, targetData) === true) {
      // If yes, then just push product Id into existing one
      current[key].productId.push(incom.productId);
      isFound = true;
    }
  }
  // if no, then create new object with as new product name
  if (isFound === false) {
    temp.productName = incom.productName;
    temp.productId = [incom.productId];
    current.push(temp);
  }
  return current;
}

function checkAlreadyExist(current, incom) {
  let result = false;
  if (current === incom) {
    result = true;
  }
  return result;
}

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You should watch out with your terminology. You are not using "JSON" here anywhere except until the end, when you call JSON.stringify(). JSON is a text format to store data. You are simply handling JavaScript objects and arrays. \$\endgroup\$
    – RoToRa
    Dec 24, 2022 at 14:44

1 Answer 1

0
\$\begingroup\$

Your code works but is really not optimized. You can use dictionnaries (Map in javascript) to improve it.

Try this:

function getStorage(incs) {
  const mapIncoming = new Map();
  const storage = {};

  // Create map with status as keys and object of products as values
  incs.forEach(({productStatus, productName, productId}) => {
    if (mapIncoming.has(productStatus)) {
        const objNames = mapIncoming.get(productStatus)
      if (objNames[productName]) {
        objNames[productName].productId.push(productId)
      } else {
        objNames[productName] = {productName, productId: [productId]}
      }
    } else {
        mapIncoming.set(productStatus, {[productName]: {productName, productId: [productId]}})
    }
  })
  
  // Convert objects stored in map into array
  for(const [status, products] of mapIncoming){
    storage[status] = Object.values(products)
  }
  
  return storage
}

console.log(getStorage(incoming))
\$\endgroup\$
1
  • \$\begingroup\$ thanks for your suggestion, I didn't expect it could be simpler. \$\endgroup\$ Nov 17, 2022 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.