Searching for items in one array within another using Lodash

Hey there! Currently utilizing the lodash library.

I'm looking to check if the phone number in receivedMessagesMock matches any of the phone numbers in contactsMocks.

If receivedMessagesMock.phone matches contactsMocks.phoneNumbers.value, I want to insert contactsMocks.name.formatted at the same position in receivedMessagesMock.

For instance:

if(receivedMessagesMock[0].phone === contactsMocks.phoneNumbers.value) {
    receivedMessagesMock[0].name = contactsMocks.name.formatted;
}

Details about the contactsMock and receivedMessagesMock:

var contactsMock = [{'id':'1','rawId':'1','displayName':'Asd','name':{'givenName':'Asd','formatted':'Asd'},'nickname':null,'phoneNumbers':[{'id':'1','pref':false,'value':'000000000','type':'mobile', 'loggedInSystem':true}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'2','rawId':'2','displayName':'Bbb','name':{'givenName':'Bbb','formatted':'Bbb'},'nickname':null,'phoneNumbers':[{'id':'3','pref':false,'value':'565 65 65 65','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'3','rawId':'3','displayName':'Ccc','name':{'givenName':'Ccc','formatted':'Ccc'},'nickname':null,'phoneNumbers':[{'id':'5','pref':false,'value':'0000000001','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'4','rawId':'4','displayName':'Ddd','name':{'givenName':'Ddd','formatted':'Ddd'},'nickname':null,'phoneNumbers':[{'id':'6','pref':false,'value':'000 00 00 01','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null}];

var receivedMessagesMock = [{
    'id': 12,
    'phone': '000 00 00 01',
    'time': '15:44',
    'priority': 1,
    'response' : false
},{
    'id': 15,
    'phone': '000 00 00 01',
    'time': '15:44',
    'priority': 1,
    'response' : false
},{
    'id': 16,
    'phone': '000 00 00 01',
    'time': '15:44',
    'priority': 2,
    'response' : true
}];

Answer №1

Here is a method using lodash for achieving this task:

lodash.map(receivedMessagesMock, function(rmm) {
  var foundContact = lodash.find(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContact) {
    rmm.names = foundContact.name.formatted
  }
  return rmm;
});

It is important to note that the goal was to insert a singular name into the received messages. In cases where multiple contacts have the same number, the code provided will only return the first match. However, there may be instances where there are multiple matches, in which case it may be more suitable to insert an array of names.

lodash.map(receivedMessagesMock, function(rmm) {
  var foundContacts = lodash.filter(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContacts.length > 0) {
    rmm.names = lodash.map(foundContacts, function(fcs) {
      return name.formatted
    });
  }
  return rmm;
});

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

The MDBDataTable features header sections at both the top and bottom, but the filters UI seems to be

Currently, I am working with MDBDataTable and encountering an issue with the double heading that appears both on top and bottom of the table. I am unsure how to remove it. The code snippet in question is as follows: There is a function that retrieves and ...

Using ${} syntax to implement dynamic logic when constructing a string in Express.js

I need to iterate through an object and display values for each one while creating a string. Any suggestions on how to achieve something like this: const body = ` <h1>Values</h1> ${ for (value in values) { return `<h2>Ind ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

What are some ways to postpone the execution of a function in React or NextJs?

How do I automatically redirect to the home page after 5 seconds of accessing a page in NextJS? I attempted to achieve this using the following code: useEffect(() => { const timer = setTimeout(() => { redirect('/home') ...

Utilizing Angular for fetching Rails ID

I am facing a challenge in my Rails 3.2 app where Angular code needs to call a Rails route and pass the id of the page. Despite embedding the id onto the page using a hidden div, accessing it from Angular to send back to Rails has proven to be difficult. ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

I'm feeling lost on how to implement a simple class pattern using object-oriented JavaScript

I've been struggling with OO Javascript and can't even recognize the same question that has been asked before. My goal is to write a Javascript class that can execute the common pattern shown below: var User=require('./models').User() ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Creating a json object using data from an HTML table

I am dealing with HTML returned from a web service that I cannot control. The HTML structure returned by the web service looks like this: <table id="result"> <tbody> <tr> <td><b>Name</b></td> < ...

How can I assign the ng-model value from an ng-repeat input in AngularJS?

I am facing an issue with allowing customers to edit a list of items using ngRepeat and ngModel. However, I am struggling to populate the input fields with the response. Here is the code snippet: <form name="customerupdateForm" ng-submit="EditCustomerS ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

What could be the reason that my Bootstrap design is displaying narrower than the designated container?

Having some issues with a JavaScript code that involves innerHTML, causing a discrepancy in width compared to the CSS and Bootstrap rules I have set up. Below is the JavaScript code snippet: let numeroStreams = document.getElementById('num') let ...

What is the best way to retrieve a unique identifier from multiple arrays and store it in one shared variable?

I have an array stored locally and I need to retrieve the "name" ID from all of them. How can I achieve this using AngularJS or JavaScript? [{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85cfeaedebc5e4abe6eae8">[ ...

Validation for a datepicker embedded within a table

I'm facing a challenge and need some assistance. I want to validate if the "FROM (DATE)" is greater than the "TO (DATE)" without disabling the date selection, but instead prompting the user if the condition is not met. Any insights or solutions would ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on th ...

Encountered a 404 error when attempting to deploy create-react-app due to failed resource loading

Any assistance would be greatly appreciated. Thank you! Although my website runs smoothly locally, I am encountering issues when trying to deploy it in a production environment. Upon executing npm run deploy, the expected outcome is an automatic build for ...

Incorporating React.js with a server API that doesn't use JavaScript

My upcoming project involves enhancing my current application frontend by implementing React.js. The existing frontend currently utilizes standard REST calls to communicate with a server built using Microsoft technologies, and there are no plans of changin ...