What is the best way to compare all the elements in an array to the entries in another object, while also storing the results of each comparison?

I am working with a JSON file that contains an array of 2 objects: `{ bg: 'a', o: 'c' }`, `{hg': 'a2', 'oo': 'c3'}`. My goal is to compare each object in the array with another object structured as follows: `{ fm: 'a', fh: 'b', o: 'a', fe: 'b', ft: 'a', fb: 'c', bg: 'f' }`. The objective is to identify if this reference object includes both sets of key/value pairs found in either of the objects within the JSON array. What would be the best approach for comparing these objects?

Answer №1

This method involves

  • Object.entries to access each key-value pair of an object in the form of [key, value].

  • Array.prototype.map to compare each entry (key-value pairs) against another provided object.

  • Array.prototype.every to check if all entries of an array-item match those of another provided object.

const sampleArr = [ { bg: 'a', o: 'c' }, {'hg': 'a2', 'oo': 'c3' } ];
const sampleObj = { fm: 'a', fh: 'b', o: 'a', fe: 'b', ft: 'a', fb: 'c', bg: 'f' };


console.log("### How `Object.entries` works ###");
console.log({
  sampleArr
});
console.log(
  "sampleArr[0] => Object.entries(sampleArr[0]) ...",
  sampleArr[0], " => ",  Object.entries(sampleArr[0])
);
console.log(
  "sampleArr[1] => Object.entries(sampleArr[1]) ...",
  sampleArr[1], " => ",  Object.entries(sampleArr[1])
);


console.log("### Comparison 1 with what was provided by the OP ###");
console.log(
  sampleArr
    // create a new array which for each ...
    .map(item => {
      // ... `sampleArr` item retrieves/maps whether ...
      return Object
        .entries(item)
        // ... every entry of such an item exists
        // as entry of another provided object.
        .every(([key, value]) => sampleObj[key] === value)
    })
);


sampleArr.push({ o: 'a', ft: 'a', fh: 'b' }); // will match     ... maps to `true` value.
sampleArr.push({ o: 'a', ft: 'X', fh: 'b' }); // will not match ... maps to `false` value.

console.log("### Comparison 2 after pushing two more items into `sampleArr` ###");
console.log({
  sampleArr
});
console.log(
  sampleArr
    // create a new array which for each ...
    .map(item => {
      // ... `sampleArr` item retrieves/maps whether ...
      return Object
        .entries(item)
        // ... every entry of such an item exists
        // as entry of another provided object.
        .every(([key, value]) => sampleObj[key] === value)
    })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Send data from input to controller without using $scope

I am encountering an issue with the code below. Typically, I would resolve this problem using $scope, but this time I have been asked to find a solution without utilizing $scope in the controller. I am implementing the "controller as" syntax for managing ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

The flow of events is not hindered by an if statement, even when the code within it is executed

I'm facing an issue where the console.log statement keeps executing even after calling the search function within the "if statements" in my code. Is there a way to prevent this from happening? function search() { /** * The Tweet checking algori ...

Communication between Nodemailer and Mailgun

I keep encountering an authentication issue while trying to use Nodemailer with Mailgun. I followed the Nodemailer documentation which states compatibility with Mailgun SMTP, but unfortunately, I am consistently facing this error when executing my applicat ...

Adding a class to the body depending on the tag or href that was clicked on the previous page

Currently, I am working on two pages - the "Home-Page" and the "Landing-Page". My goal is to customize the content of the "Landing-Page" based on the button clicked on the previous page (which happens to be the "Home-Page"). Initially, I tried using ancho ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

What are the steps for modifying JSON Arrays?

Looking for a way to streamline my JSON array by removing unwanted keys and simplifying the structure. Any recommendations on software or websites that can help with this task? Basically, I want to transform data like this: "一": { "st ...

Activating Unsplash API to initiate download

I am currently following the triggering guidelines found in the Unsplash documentation. The endpoint I am focusing on is: GET /photos/:id/download This is an example response for the photo: { "id": "LBI7cgq3pbM", "width": ...

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

I am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Modify the name of the selected option value

I am working on an html code where I need to replace the values 0, 1, and 2 with USA, Australia, and Canada respectively. I also need to know the name of these values in my MySQL database. Thanks! HTML <form method="post" id="countriesForm" name="cou ...

Is it possible to attach a Vue component to more than one div element simultaneously?

import Selector from '@components/contactSelector' let vueInstance = new Vue({ components: { Selector }, data () { return { url: url, isFilter: false, type: 'external', selectedList: [] } }, rende ...

Trigger a JavaScript alert message upon clicking the close button

I have encountered an issue with my current code. When I click on the close (X) button, it should display an error message stored in variable s. Previously, the script was functioning correctly but now it is not showing any alerts when I click on the close ...

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

Unable to retrieve coverage report using rewire and cross-env

My challenge lies in obtaining the coverage report using nyc, which works flawlessly without the cross-env plugin. cross-env NODE_ENV=test nyc mocha --ui bdd --reporter spec --colors --require babel-core/register tests --recursive When executing this com ...

Capture data from clipboard as it is being pasted into Handsontable

Issue Description and Troubleshooting: In a nutshell, I am seeking a method to manage data copied from the clipboard to a handsontable. I came across a suggestion on how to fetch this information using jQuery in a stackoverflow post: $("#haras_excel_li ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

Sequelize - issue with foreign key in create include results in null value

When using the create include method, the foreign key is returning null, while the rest of the data is successfully saved from the passed object. This is my transaction model setup: module.exports = (sequelize, DataTypes) => { const Transaction = ...