[Solved] Merging Object In Array In JavaScript if Conditions Are Met [closed]


Here is the steps which you need to follow.

  • Create a new array for merged objects
  • Iterate the array
  • Find the item which you’re looking for
  • merge with the existing object to the filtered object
  • append to new object
  • done.
let json = [{"id":191,"warehouse_id":24,"ingredient_id":65,"expiration_date":"2019-07-31","available_stocks":7,"ingredient":{"id":65,"name":"erg","SKU":"1000064","default_unit":{"id":26,"name":"Milliliter"},"purchase_price":50}},{"id":192,"warehouse_id":24,"ingredient_id":66,"expiration_date":"2019-09-18","available_stocks":33994,"ingredient":{"id":66,"name":"gvf","SKU":"1000065","default_unit":{"id":27,"name":"Gram"},"purchase_price":60}},{"id":193,"warehouse_id":24,"ingredient_id":67,"expiration_date":"2019-09-19","available_stocks":43996,"ingredient":{"id":67,"name":"fwefe","SKU":"1000066","default_unit":{"id":26,"name":"Milliliter"},"purchase_price":70}},{"id":52,"outlet_item_id":null,"warehouse_item_id":191,"ingredient_id":65,"quantity":7,"total_in_lowest":0,"stock_on_hand":0,"adjustment_price":0,"soh_total_in_lowest":0,"unit_price":50,"difference":0,"difference_in_lowest":0}];

// new array after merging the objects 
let desiredArray = [];
// iterate the array
let processedWarehouseItems = [];
for (let i = 0; i < json.length; i++) {
  let newObj = json[i]; // assign the each object if no filtered found in case
  // find the object based on your filter condition
  let fiteredObj = json.filter(
    e => e.id != json[i].id && e.warehouse_item_id === json[i].id
  );
  if (fiteredObj && fiteredObj.length) {
    // if object found
    processedWarehouseItems.push(fiteredObj[0].warehouse_item_id);
    newObj = { ...json[i], ...fiteredObj[0]
    }; // merge the objects and creates a new one
  }

  // check if the item is already merged in?
  if (processedWarehouseItems.indexOf(json[i].warehouse_item_id) === -1) {
    desiredArray.push(newObj); // push to the new array
  }
}
console.log(desiredArray)

4

solved Merging Object In Array In JavaScript if Conditions Are Met [closed]