Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data.

this.linkedParticipants =[
  {
    "id": 3,
    "name": "Participant 2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f0e1f2f4e9e3e9f0e1eef4b2c0e6e9e3efaee3efed">[email protected]</a>"
  },
  {
    "id": 2,
    "name": "Participant 1",
    "email"": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2829380869b919b82939c86c3b2949b919ddc919d9f">[email protected]</a>"
  },
  {
    "id": 1,
    "name": "Libin Varghese",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d599bcb7bcbb83b4a7b2bdb0a6b095b3bcb6bafbb6bab8"><email protected></a>"
  },
  {
    "id": 7,
    "name": "Participant 5",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9c9d8cbcdd0dad0c9d8d7cd8cf9dfd0dad697dad6d4"><email protected></a>"
  }
]
this.appointmentList = [
  {
    "id": 32,
    "participant": {
      "id": 1,
      "name": "Libin Varghese",
      "email": "<a href="mailto: [email protected]><email protected></a>"
    }
  },
  {
    "id": 33,
    "participant": {
      "id": 7,
      "name": "Participant 5",
      "email": "<a href="mailto: [email protected]><email protected></a>"
    }
  }
]
this.invitedList = [];
this.confirmedList = [];
let temp = {}
this.linkedParticipants.forEach((participant, i) => {
  this.appointmentList.forEach((appointment, j) => {
    if (appointment.participant.name.indexOf(participant.name)) {
      temp = {
        'participant': participant
      }
      this.invitedList.push(temp);
    }
    else {
      this.confirmedList.push(appointment)
    }
  })
})

However, I am encountering an issue where the code is producing duplicate values in the invited list. It seems like there might be some problem with my comparison condition.

Answer №1

To accomplish this task, you can utilize various combinations of the filter() method:

 var usersList =[
  {
    "id": 3,
    "name": "User 2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e1e0f1c1a070d071e0f001a5c2e08070d01400d0103">[email protected]</a>"
  },
  {
    "id": 2,
    "name": "User 1",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91e1f0e3e5f8f2f8e1f0ffe5a0d1f7f8f2febff2fefc">[email protected]</a>"
  },
  {
    "id": 1,
    "name": "John Doe",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="531f3a313a3d053221343b36203613353a303c7d303c3e">[email protected]</a>"
  },
  {
    "id": 7,
    "name": "User 5",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2a3b282e3339332a3b342e6f1a3c33393574393537">[email protected]</a>"
  }
];
var userListA = [
  {
    "id": 32,
    "user": {
      "id": 1,
      "name": "John Doe",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8f4d1dad1d6eed9cadfd0ddcbddf8ded1dbd796dbd7d5">[email protected]</a>"
    }
  },
  {
    "id": 33,
    "user": {
      "id": 7,
      "name": "User 5",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76061704021f151f061718024336101f15195815191b">[email protected]</a>"
    }
  }
];


var activeUsers = userListA.filter((a) => {
  return usersList.find((u) => u.id === a.user.id);
});

var inactiveUsers = usersList.filter((u) => {
  return !userListA.find((a) => u.id === a.user.id);
});

console.log(activeUsers)
console.log(inactiveUsers)

Answer №2

can be achieved by utilizing the filter and comparer function.

 const linkedParticipants =[
      {
        "id": 3,
        "name": "Participant 2",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f888998a8c919b918899968ccab89e919b97d69b9795">[email protected]</a>"
      },
      {
        "id": 2,
        "name": "Participant 1",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140516100d070d14050a105524020d070b4a070b09">[email protected]</a>"
      },
      {
        "id": 1,
        "name": "Libin Varghese",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88c4e1eae1e6dee9faefe0edfbedc8eee1ebe7a6ebe7e5">[email protected]</a>"
      },
      {
        "id": 7,
        "name": "Participant 5",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63130211170a000a13020d175623050a000c4d000c0e">[email protected]</a>"
      }
    ]
    const appointmentList = [
      {
        "id": 32,
        "participant": {
          "id": 1,
          "name": "Libin Varghese",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98d4f1faf1f6cef9eafff0fdebfdd8fef1fbf7b6fbf7f5">[email protected]</a>"
        }
      },
      {
        "id": 33,
        "participant": {
          "id": 7,
          "name": "Participant 5",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8b8a9babca1aba1b8a9a6bcfd88aea1aba7e6aba7a5">[email protected]</a>"
        }
      }
    ]


    function comparer(otherArray){
        return function (current) {
            return otherArray.filter(function(other) {
                return other.id === current.id
            }).length===0;
        }
    }

   

   const invitedList = appointmentList.map(i=> {return i.participant});


    const confirmedList=linkedParticipants.filter(comparer(invitedList ));
    
    console.log(invitedList);
    console.log(confirmedList)

Answer №3

If you're looking to find an intersection, utilizing the Set method can be helpful. The typical approach involves:

function intersect(a, b) {
  const setB = new Set(b);
  return [...new Set(a)].filter(x => setB.has(x));
}

To address your question, you could achieve your objective with:

function intersect(linkedParticipants, appointmentList) {
  const setB = new Set(linkedParticipants);
  return [...new Set(appointmentList)].filter(({participant}) => setB.has(participant));
}

I usually structure arrays in this manner:

const id1 = {
    "id": 1,
    "name": "Libin Varghese",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74381d161d1a221506131c11071134121d171b5a171b19">[email protected]</a>"
  };
const id2 = {
    "id": 2,
    "name": "Participant 1",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a6b7a4a2bfb5bfa6b7b8a2e796b0bfb5b9f8b5b9bb">[email protected]</a>"
  };
const id3 = {
    "id"&quo: 3,
    "name": "Participant 2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6d7c6f69747e746d7c73692f5d7b747e72337e7270">[email protected]</a>"
  };
const id7 = {
    "id": 7,
    "name": "Participant 5",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a3b2a1a7bab0baa3b2bda7e693b5bab0bcfdb0bcbe">[email protected]</a>"
  };
const linkedParticipants =[id1, id2, id3, id7]
const appointmentList = [
  {
    &qut:id": 32,
    "participant": id1
  },
  {
    "id": 33,
    "participant": id7
  }
];

https://i.sstatic.net/oqtZw.png Just a friendly reminder that objects are reference types.

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

Creating a bar chart in Chart JS using an array of data objects

I need to create a unique visualization using a bar chart where each bar represents a user or student. Each bar will have an xAxis label displaying the student's name. The code below is a VueJS computed property named chartData For my bar chart data ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

After implementing two hooks with null properties, the code fails to execute

Recently, I encountered an issue with this section of the code after upgrading react scripts from version 2.0 to 5.0. const { user, dispatch } = useContext(AuthContext); const { data } = useFetch(`/contracts/${user.contractType}`); if (!user) { ...

What is the best way to iterate through a designated key in every object within a JSON dataset and store it in a variable called `data` for use with

I am looking to create a line chart displaying stock prices, utilizing JSON data to populate the chart. Let's say I have some JSON data: [ { "close": 116.59, "high": 117.49, "low": 116.22, "open& ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

What steps are necessary to ensure that the extended attribute becomes mandatory?

Utilizing Express, I have set specific fields on the request object to leverage a TypeScript feature. To achieve this, I created a custom interface that extends Express's Request and includes the additional fields. These fields are initialized at the ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...

The enigma of the Angular2 Object's Undefined nature

Encountering an "object undefined" error when trying to access the object of the Service Component. Interestingly, hard coding the data directly into a JavaScript variable works fine and shows the type as "object Array." Data.json [ { "id": ...

Firebase version 9 - Retrieve the content of a referenced document

I'm having trouble locating the documentation I need. Within my Firebase Firestore project, there is a collection called users. Within users, there are three collections: companies, policies, and stores. In the policies collection, I have fields for ...

Is Local Storage compatible with phonegap?

I am looking to integrate local storage into my phonegap application in order to store an array of data. Here is a snippet of my code: <div data-role="collapsibleset"> <div data-role="collapsible"> <h3>LOG ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

Tips for resolving the error message "TypeError: Cannot access property 'category' of undefined" while working in a React environment

Hey there, I encountered an issue while trying to destructure in react and can't figure out why the title is appearing as an error message. Below is the code snippet: const {correct_answer, incorrect_answers} = data[0] const arr = [correct_answer, ... ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

Blend Image and Text with jQuery when Hovered Over

Alright, so here's the deal - I have an image that needs to smoothly transition to another image when hovered over. I also have some descriptive text that should crossfade into different text corresponding to the second image. The current setup is ki ...

I have a parent DIV with a child DIV, and I am looking to use jQuery to select the last child DIV. The parent DIV has an

In my HTML code, I have a parent div called "allcomments_4" which contains several child divs with unique IDs (oneEntry), each with their own children. My goal is to locate and retrieve the content inside the last child of the parent node (lastComment) and ...

Step-by-step guide on displaying a fresh page within a JavaScript code

I've been working with XHTML, JSF, and JavaScript to develop a form that validates user input in selected fields when a button is clicked. The goal is to redirect the user to a different page called homepage.xhtml after successful validation. However, ...