Assign the same property value to all objects in the array and remove any duplicates

I am currently working with an object that contains nested objects:

{
  "0": {
    "boardingGate": "exit_0",
    "departureTerminal": "1",
    "terminalArea": 0,
    "arrivalGate": "enter_0",
    "arrivalTerminal": "2",
    "terminalArea": 0
  },
  "1": {
    "boardingGate": "exit_1",
    "departureTerminal": "1",
    "terminalArea": 0,
    "arrivalGate": "enter_1",
    "arrivalTerminal": "2",
    "terminalArea": 0
  },
  "2": {
    "boardingGate": "exit_0",
    "departureTerminal": "1",
    "terminalArea": 0,
    "arrivalGate": "enter_0",
    "arrivalTerminal": "3",
    "terminalArea": 0
  },
  "3": {
    "boardingGate": "exit_1",
    "departureTerminal": "2",
    "terminalArea": 0,
    "arrivalGate": "enter_1",
    "arrivalTerminal": "3",
    "terminalArea": 0
  }
}

My task is to update all "boardingGate" values to "exit_0" and all "arrivalGate" values to "enter_0". After this transformation, any objects with identical structures should be removed. The desired output after these operations is as follows:

{
  "0": {
    "boardingGate": "exit_0",
    "departureTerminal": "1",
    "terminalArea": 0,
    "arrivalGate": "enter_0",
    "arrivalTerminal": "2",
    "terminalArea": 0
  },
  "1": {
    "boardingGate": "exit_0",
    "departureTerminal": "1",
    "terminalArea": 0,
    "arrivalGate": "enter_0",
    "arrivalTerminal": "3",
    "terminalArea": 0
  },
  "2": {
    "boardingGate": "exit_0",
    "departureTerminal": "2",
    "terminalArea": 0,
    "arrivalGate": "enter_0",
    "arrivalTerminal": "3",
    "terminalArea": 0
  }
}

I have attempted a solution using forEach by accessing Object.values(data), but I haven't been able to achieve the desired outcome. I'm unsure if there's a simpler approach to solving this problem.

    const tickets = Object.values(data);

    tickets.forEach((next, index, ticket) => {
      const boardingGateKeys: any = Object.keys(next.boardingGate);
      const boardingGateValues: any = Object.values(next.boardingGate);

      boardingGateKeys.forEach((gate, gateIndex) => {
          const arrivalGateKeys: any = Object.keys(gate.outputs);
          const arrivalGateValues: any = Object.values(gate.outputs);
          arrivalGateValues.forEach((output, outputIndex) => {

              });
            }
        });
      });

Your assistance with this problem would be greatly appreciated. Thank you in advance.

Answer №1

To extract the relevant entries, you can trim the array to only include the desired common entries and introduce a new data set for any unknown key/value pairs with updated properties.

Finally, construct an object from the modified array.

var data = { 0: { boardingGate: "exit_0", departureTerminal: "1", terminalArea: 0, arrivalGate: "enter_0", arrivalTerminal: "2" }, 1: { boardingGate: "exit_1", departureTerminal: "1", terminalArea: 0, arrivalGate: "enter_1", arrivalTerminal: "2" }, 2: { boardingGate: "exit_0", departureTerminal: "1", terminalArea: 0, arrivalGate: "enter_0", arrivalTerminal: "3" }, 3: { boardingGate: "exit_1", departureTerminal: "2", terminalArea: 0, arrivalGate: "enter_1", arrivalTerminal: "3" } },
    result = Object.assign({}, Object
        .values(data)
        .reduce((r, { boardingGate, arrivalGate, ...o }) => {
            const entries = Object.entries(o);
            if (!r.some(q => entries.every(([k, v]) => q[k] === v))) {
                r.push({ boardingGate: "exit_0", arrivalGate: "enter_0", ...o });
            }
            return r;
        }, [])
    );

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Concerns have been raised about your code:

  • The first concern is minor (both the input and expected objects are invalid due to the duplicate terminalArea key)
  • The major concern is that both your attempted solution and accepted answer are implementing O(n²)-time algorithms (due to nested loops), which could lead to significant performance loss (up to 90% slower compared to an O(n)-time algorithm for 1k items) if the input size is large enough.

If you are looking for a more comprehensive (and more importantly, faster) alternative, consider the following approach:

  • Create a hash map containing unique combinations of input object values
  • Add remapped objects (with standardized values of boardingGate/arrivalGate) only if their hash is not present in the hashmap

The proof of concept is demonstrated below:

const src = {"0":{"boardingGate":"exit_0","departureTerminal":"1","departureTerminalArea":0,"arrivalGate":"enter_0","arrivalTerminal":"2","arrivalTerminalArea":0},"1":{"boardingGate":"exit_1","departureTerminal":"1","departureTerminalArea":0,"arrivalGate":"enter_1","arrivalTerminal":"2","arrivalTerminalArea":0},"2":{"boardingGate":"exit_0","departureTerminal":"1","departureTerminalArea":0,"arrivalGate":"enter_0","arrivalTerminal":"3","arrivalTerminalArea":0},"3":{"boardingGate":"exit_1","departureTerminal":"2","departureTerminalArea":0,"arrivalGate":"enter_1","arrivalTerminal":"3","arrivalTerminalArea":0}},

      remapDedupe = input => {
        const hashMap = new Set(),
              result = []
        for(idx in input){
          const {boardingGate, arrivalGate, ...rest} = input[idx],
                hash = Object.values(rest).join('|')
          if(hashMap.has(hash)) continue               
          result.push({
            boardingGate: 'exit_0', 
            arrivalGate: 'enter_0', 
            ...rest
          })
          hashMap.add(hash)
        }
        return {...result}
      },
      
      result = remapDedupe(src)
        
console.log(result)

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

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...

Looking for a dropdownlist with checkboxes in asp.net mvc but without the use of Entity Framework

I am in need of a dropdown list with checkboxes in asp.net mvc. The issue is that my view already has a layout page with existing script files, which seem to be causing a disturbance in the original layout. I have tried various solutions such as rearrangi ...

After removing the div element, the error message 'Cannot read property 'offsetWidth' of undefined or null reference' is displayed

Currently, I am encountering an error on my website stating "Cannot read property 'offsetWidth' of undefined or null reference" after commenting out 2 divs in a bootstrap carousel. The carousel was created by someone who is not available to me at ...

JavaScript or jQuery for filtering table rows

I have limited experience with JavaScript and jQuery, but I am working with a table containing various entries. My goal is to implement a filtering system using a list on the left side of the table. Here is an example I put together: http://jsfiddle.net/B ...

Creating every potential expression that satisfies a given grammar can be achieved by following these steps

I have developed a grammar for my application that includes the following expressions: (FIND, SEARCH, Lookup) [a, the, an, for] ITEM [in, at] (NEST, SHELF, DESK) The expressions consist of required items in round brackets "()", optional items in square b ...

Guide on saving multiple PDF files in the public directory using Laravel 8 controllers

I am currently facing a challenge in storing my PDF files in the public folders. Does anyone have any suggestions on how to achieve this? I attempted to iterate through the data to access the file, but unfortunately, it is not working as expected on my en ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

What is the best way to clear memory after using a temporary THREE.js renderer and container?

Within my javascript "Image SNAP Function," I am utilizing a temporary DOM div container along with a THREE.js renderer to generate a high-resolution image file of the current scene. This allows the user to view the image outside the browser or save it as ...

Tips for Managing the Hardware Back Button in Ionic 3

Can someone help me enable the hardware back button in Ionic 3? I want it to redirect to specific pages and display designated content. Being new to Ionic 3, I need guidance on how to set up the hardware device buttons for redirection. ...

Grabbing <object> HTML using jQuery

One example on my webpage is the presence of the following <object>: <object id="obj1" data="URL"></object> Could you please suggest a method to access this html object using jQuery? ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

What is the best way to create a large array (26000 x 26000) in PHP?

Can I create an array in PHP with dimensions of 26000 x 26000? I attempted to make one with dimensions of 10000 x 10000, but encountered the following error: Fatal error: Out of memory (allocated 1886388224) (tried to allocate 24 bytes) in C:\xampp ...

Present timestamp using the date API format of YouTube

I'm working with the YouTube API, which provides uploaded and updated times in this format: 2013-05-13T13:12:42.000Z (ISO 8601). How can I use Javascript or jQuery to get the relative time? Despite trying various sources, the date formatting seems to ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

How to Utilize ngIf and ngFor Together in Angular 4 for the Same Element in ngFor

Just starting with Angular 4 and experiencing a roadblock in my code. Here is the snippet of my code: JSON: [{"name": "A", "date": "2017-01-01", "value": "103.57"}, {"name": "A", "date": "2017-01-08", "value": "132.17"}, ...

What is the best way to set a button as the default option when it is pressed down?

<div class="input-group"> <input type="text" id="srcSchtext" class="form-control" runat="server" placeholder="Search here..." /> <span class="input-group-btn"> <asp:Button runat="server" ID="btnSearchEmployee" ...

Is there a way to troubleshoot and improve my Discord bot's kick functionality?

I'm having an issue with my code. When I type in the command "exp kick @user being toxic", it doesn't do anything. It seems to be ignoring my command. Here is the code snippet that I'm using: client.on("message", message => { var comm ...