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

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Experience the seamless transition of new CSS animations

I designed a basic HTML game where a moving box disappears when clicked on. However, the animation that follows does not originate from the click location but rather from the original position. I believe the remove @keyframes at 0% should be based on the ...

Is there a way to identify the element causing an error in promise.map and then either log it to the console or skip it using code?

When running the code provided below, I encounter a 500 error for certain URLs in my list due to the structure of the page. The error occurs specifically on the line .map((htmlOnePage, index) => when some URLs lead to invalid pages, causing the prog ...

Trigger the submission of Rails form upon a change in the selected value within a dropdown form

I am working on a Rails application that has a table of leads. Within one of the columns, I display the lead's status in a drop-down menu. My goal is to allow users to change the lead's status by simply selecting a different value from the drop-d ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

Display custom modals in React that showcase content for a brief moment before the page refreshes

I recently developed a custom modal in React. When the Open button is clicked, showModal is set to true and the modal display changes to block. Conversely, clicking the Close button sets the display to none. However, I noticed a bug where upon refreshing ...

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...

Convert CSV data into an array and assign keys

Hello everyone! I've created a simple CSV file importer and key assigner in PHP. I'm new to PHP and would love some feedback on how to improve this code. I really appreciate the help from this forum as I continue learning. Thanks! <?php $csvf ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

Generating JSON on-the-fly with fluctuating keys and values in conjunction with Express JS

When I fetch an API into my Express server, the data comes in the form of JSON key-value pairs within an array. [{ "quality": "best", "url": "https://someurlhere.example/?someparameters" }, { "quality": ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...

The disappearing act of Redux state after being added to a nested array

When attempting to update my redux state, I am facing an issue where the state disappears. My approach involves checking for a parentId - if one exists, I insert the payload into the parent's children array. However, if no parentId is provided, I simp ...