What is the best way to categorize elements in an array of objects with varying sizes based on two distinct properties in JavaScript?

I am faced with a scenario where I have two distinct arrays of objects obtained from an aggregate function due to using two different collections.

Although I attempted to utilize the map function as outlined here, it proved unsuccessful in resolving my issue. What other strategies can I employ to achieve the desired outcome?

  qrySearch = [{
    sName: 'SomePlace1',
    lBusinessID: 37343,
    SystemID: 5000152
  },
  {
    sName: 'SomePlace2',
    lBusinessID: 39780,
    SystemID: 5000156
  },
  {
    sName: 'SomePlace3',
    lBusinessID: 50772,
    SystemID: 5000519
  },
  {
    sName: 'SomePlace4',
    lBusinessID: 31079,
    SystemID: 5000384
  }
]

and

qrySearchLocID = [{
    LocalLabID: '123f',
    _ID: 'SomePlace1',
    AppLabID: 3,
    count: 15   
  },
  {
    LocalLabID: '12BC',
    _ID: 'SomePlace2',
    AppLabID: 3,
    count: 40
  }
];

After attempting the result extraction, only this array is obtained:

qrySearch = [{
    sName: 'SomePlace1',
    lBusinessID: 37343,
    SystemID: 5000152
  },
  {
    sName: 'SomePlace2',
    lBusinessID: 39780,
    SystemID: 5000156
  },
  {
    sName: 'SomePlace3',
    lBusinessID: 50772,
    SystemID: 5000519
  },
  {
    sName: 'SomePlace4',
    lBusinessID: 31079,
    SystemID: 5000384
  },
]

To simplify matters, the array has been kept brief. The main requirement is to cross-reference the _ID if it corresponds to sName for the desired outcome:

result = [{
        sName: 'SomePlace1',
        lBusinessID: 37343,
        SystemID: 5000152,
        LocalLabID: '123f',
        AppLabID: 3,
        count: 15
      },
      {
        sName: 'SomePlace2',
        lBusinessID: 39780,
        SystemID: 5000156,
        LocalLabID: '12BC',
        AppLabID: 3,
        count: 40
      },
      {
        sName: 'SomePlace3',
        lBusinessID: 50772,
        SystemID: 5000519
      },
      {
        sName: 'SomePlace4',
        lBusinessID: 31079,
        SystemID: 5000384
      }
    ]

Even though I experimented with this approach:

var result = qrySearch.map((e, _) => 
          (_ = qrySearchLocID.find((q) => q._ID=== e.sName)) ? 
          { ...e, ...{ _ID: _._ID} } : e);

The outcome lacked the count information.

Answer №1

To effectively combine the values, simply spread your placeholder _

const searchQueries = [
    {
        placeName: 'Location1',
        businessID: 37343,
        ID: 5000152
    },
    {
        placeName: 'Location2',
        businessID: 39780,
        ID: 5000156
    },
    {
        placeName: 'Location3',
        businessID: 50772,
        ID: 5000519
    },
    {
        placeName: 'Location4',
        businessID: 31079,
        ID: 5000384
    },
];

const searchLocQueries = [
    {
        LabID: '123f',
        _ID: 'Location1',
        AppLabID: 3,
        count: 15
    },
    {
        LabID: '12BC',
        _ID: 'Location2',
        AppLabID: 3,
        count: 40
    },
];

var result = searchQueries.map((element, index) =>
          (index = searchLocQueries.find((query) => query._ID === element.placeName)) ?
          { ...element, ...index }: element);
console.log(result);

Answer №2

Develop a process that combines two arrays, organizes them by the sName or _ID, and then maps all groups into a new merged object:

const { flow, concat, groupBy, map, merge, partialRight: pr } = _;

const combine = flow(
  concat,
  pr(groupBy, obj => obj.sName || obj._ID),
  pr(map, group => merge({}, ...group))
);

const qrySearch = [{"sName":"SomePlace1","lBusinessID":37343,"SystemID":5000152},{"sName":"SomePlace2","lBusinessID":39780,"SystemID":5000156},{"sName":"SomePlace3","lBusinessID":50772,"SystemID":5000519},{"sName":"SomePlace4","lBusinessID":31079,"SystemID":5000384}];

const qrySearchLocID = [{"LocalLabID":"123f","_ID":"SomePlace1","AppLabID":3,"count":15},{"LocalLabID":"12BC","_ID":"SomePlace2","AppLabID":3,"count":40}];

const result = combine(qrySearch, qrySearchLocID);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Implementing the same concept using lodash/fp:

const { flow, concat, groupBy, map, mergeAll, propOr } = _;

const combine = flow(
  concat,
  groupBy(obj => obj.sName || obj._ID),
  map(mergeAll)
);

const qrySearch = [{"sName":"SomePlace1","lBusinessID":37343,"SystemID":5000152},{"sName":"SomePlace2","lBusinessID":39780,"SystemID":5000156},{"sName":"SomePlace3","lBusinessID":50772,"SystemID":5000519},{"sName":"SomePlace4","lBusinessID":31079,"SystemID":5000384}];

const qrySearchLocID = [{"LocalLabID":"123f","_ID":"SomePlace1","AppLabID":3,"count":15},{"LocalLabID":"12BC","_ID":"SomePlace2","AppLabID":3,"count":40}];

const result = combine(qrySearch, qrySearchLocID);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

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

Using the input method in JavaScript cannot extract an object property

Recently, I have been working with this JavaScript code provided below. It is essential for me to retrieve the votecount for a game based on user input. function Game(gamename,votes) { this.gamename = gamename; this.votes = votes; }; var lol = ne ...

`How can I enable the download attribute feature on Safari browser?`

Is there a workaround for saving files with a specified name in Safari? The following HTML code does not work properly in Safari, as it saves the file as 'unknown' without an extension name. <a href="data:application/csv;charset=utf-8,Col1%2C ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Is there a way to instantly show the contents of a newly opened tab in BootstrapVue?

Good day, my objective is as follows: Whenever a new tab is opened, it should become 'active' and display its content on the browser Issue: Currently, when a new tab is opened, the previous tab remains 'active'. Check out a simple e ...

What steps should I take to ensure that the getElementsbyName function works properly on both Internet Explorer and Firefox browsers

Encountering a JavaScript error in IE but not in FF ("document.getelementsbyname(...).0.innerhtml is null or not an object": var oldVal = parseInt(document.getElementsByName("outSL")[0].innerHTML); //value pulled from the database Here is the asp.net c ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Execute a function singularly upon vertical scrolling upwards or downwards

Looking for a solution to load two distinct animated graphics on a website when scrolling up or down, I managed to trigger the desired functions. However, there seems to be a bug where the functions are being triggered excessively: $(window).scroll(func ...

Ways to stop CKEDITOR from automatically saving textarea or contenteditable content

I've integrated the CKEDITOR plugin for a format toolbar feature on my web application. It seems that the message shown above is a default one provided by CKEDITOR. My goal is to have users start with a blank textarea every time they visit the page, ...

Need help in setting the default TIME for the p-calendar component in Angular Primeng version 5.2.7?

In my project, I have implemented p-calendar for selecting dates and times. I have set [minDate]="dateTime" so that it considers the current date and time if I click on Today button. However, I would like the default time to be 00:00 when I click ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Using HTML and JavaScript to implement a dragging functionality on a canvas element

After creating a square grid using HTML canvas, I've added a drag feature that allows users to draw rectangles by dragging over the grid. However, it seems that non-rectangle shapes can also be drawn in certain cases. Let's delve into an additio ...

Display the user's location on Google Maps in addition to all other markers for a comprehensive view

How can I modify the code to prompt the user for their location only when they click on a specific button, and then show all markers on the map? This jsfiddle illustrates the current issues: Google map loads markers from a database, and the user is asked b ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Ways to eliminate an object from an array using Javascript or Jquery

I have two arrays of objects (with the same properties) where I need to remove all objects with the same name as those found in filesToRemove from the array files. However, when I attempt to use the code below, it throws an error: Uncaught TypeError: fil ...

Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below: let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { na ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

JavaScript encounters an unexpected identifier: Syntax Error

I encountered a syntax error while executing the code below: var userAnswer = prompt("Do you want to race Bieber on stage?") if userAnswer = ("yes") { console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!") } else { ...

When using TypeScript in React, the event handler for the onLoad event of an image element cannot locate the properties naturalWidth and naturalHeight

https://i.sstatic.net/vPfkL.png return <img {...props} onLoad={event => { console.log(event.target.naturalWidth) }}/> I am encountering an issue trying to access naturalWidth and naturalHeight in TypeScript React. Unfortunately, TypeScript is ...

Generate a new TreeView using the checked checkboxes from a current TreeView

I am currently working on implementing a dynamic user access feature for specific nodes within an existing treeview that is also dynamic. The primary TreeView that I am using contains checkboxes and gets populated from a database. Additionally, there is a ...