Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Please refer to the code snippet and JSON response below.

CODE

const yeah = yes.filter(a => a.id === a.warehouse_item_id);

JSON Response

yes = [
  {
    "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
  }
]

EXPECTED OUTPUT

[
              {
                "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,
                  "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
              },
              {
                "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
              }
            ]

        > EXPECTED OUTPUT
        yes = [
          {
            "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
            }
          }
        ]

Answer №1

Here are the necessary steps to complete the task:

  • Start by creating a new array to store merged objects
  • Iterate through the existing array
  • Locate the specific item you are searching for
  • Merge it with the existing object to create a filtered object
  • Append the filtered object to the new array
  • Task completed!

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}];
    
// Create a new array to hold the merged objects
let desiredArray = [];
// Iterate through the array
let processedWarehouseItems = [];
for (let i = 0; i < json.length; i++) {
  let newObj = json[i]; // Assign each object if no filtered item is found
  // Find the object based on the filter condition
  let filteredObj = json.filter(
    e => e.id != json[i].id && e.warehouse_item_id === json[i].id
  );
  if (filteredObj && filteredObj.length) {
    // If object is found, merge and create a new one
    processedWarehouseItems.push(filteredObj[0].warehouse_item_id);
    newObj = { ...json[i], ...filteredObj[0]
    };
  }

  // Check if the item has already been merged
  if (processedWarehouseItems.indexOf(json[i].warehouse_item_id) === -1) {
    desiredArray.push(newObj); // Add to the new array
  }
}
console.log(desiredArray)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

What is the process for creating a hover linear wipe transition using CSS/JS?

It's worth noting that I can't simply stack one image on top of the other because I'll be dealing with transparent images as well. preview of linear wipe ...

The request for the print member, which is a non-class type of 'char', encountered an error

Whenever I attempt to execute my print function, I receive the following error message: SalesDB.cpp:61:19: error: request for member ‘print’ in ‘((SalesDB*)this)->SalesDB::salesPerson[i]’, which is of non-class type ‘char’ salesPerson[i].pr ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

Exploring the properties within a MongoDB document using mapping functionality

I am trying to retrieve data from a document using Node.js and encountering an issue where the map operator is returning data with similar names twice. I am wondering if I can use filter instead of map to address this problem. Here is the code I am using t ...

The Android webview is blocking the display of a frame due to its X-Frame-Options being set to 'DENY'

Encountering an issue while attempting to display a Google calendar in a webview, an error is displayed: [INFO:CONSOLE(0)] "Refused to display 'https://accounts.google.com/ServiceLogin?service=cl&passive=1209600&continue=https://www.google.co ...

Retrieving status code without reliance on a back-end language (maybe through JavaScript?)

My new service offers a solution for error pages in web apps by providing a code snippet that can be easily copied and pasted into the error page templates, similar to Google Analytics. The status code is embedded in a hidden input within the installatio ...

The .removeAttr('checked') method fails to function as expected

I am currently using CodeIgniter. Check out this example of my code. Please fill the textbox and check the checkbox next to it, then click on the "add" link. You will notice that it does not work as expected..removeAttr('checked') newDiv.find(&a ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Using TypeScript with knockout for custom binding efforts

I am in the process of developing a TypeScript class that will handle all bindings using Knockout's mechanisms. Although I have made progress with the initial steps, I have encountered a roadblock. While I can successfully bind data to my HTML element ...

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

Incorporating the inputted year into the AJAX request

At page A, there is a form that includes an input field for the year and a dropdown menu for selecting a month. <form method="post" action="" name="form_cal" id="form_cal" class="inputform"> <div class="h5"><stro ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

"Concealing specific routes in Vue Router depending on a certain condition - what's the

I need to determine which routes to hide based on a condition that evaluates to true or false. I have a collection of routes, such as: - Products - Clients For instance, if a user logs in but does not have the permission to edit products, then the updated ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

Eliminate redundant information from the array

I am dealing with 2 different arrays. const finalArr = [] const arr = ["abc","def"] const arr2 = [ { name: "abc", refresh: false }, { name: "efd", refresh: false }, { name: "def", refresh: false } ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

What could be causing my issue with the if-else condition not functioning properly?

Why does the code only work for adding and removing styles in Part (else), but not returning the class when clicked again? var navDropDown = document.querySelectorAll('.menu-item-has-children > a'); for (let i = 0; i < navDropDown.length; i ...