Sort through object attributes according to a different object

I have two sets of data represented by objects object_a and object_b. I want to extract the items from object_a that correspond to the IDs found in object_b.

const object_a = {
    100: "Stack Overflow",
    101: "MDN Web Docks",
    102: "Javascript"
}

const object_b = {
    0: {
        id: 100,
        name: "Stack",
        lastname: "Overflow"
    },
    1: {
        id: 101,
        name: "Web",
        lastname: "Docks"
    }
}   

My goal is to create a new object containing the items from object_a whose IDs are present in object_b.

const desired_object = {
    100: "Stack Overflow",
    101: "MDN Web Docks"
}

Answer №1

To enhance your code structure, consider utilizing the Object.entries() method on object_a and then employing Array.prototype.filter() to exclude elements that are not included (using Array.prototype.some()) in the id values of object_b:

const a = {100:"Stack Overflow", 101:"MDN Web Docks", 102:"Javascript"},
      b = {0:{id:100, name:'Stack', lastname:'Overflow'}, 1:{id:101, name:'Web', lastname:'Docks'}},
    
    result = Object.fromEntries(
      Object
        .entries(a)
        .filter(([key]) => 
          Object
            .values(b)
            .some(({id}) => id == key)
        )
     )
    
console.log(result)

Alternatively, for potentially improved performance, you can utilize Array.prototype.reduce() to loop through the Object.keys() of object_a and carry out the same validation:

const a = {100:"Stack Overflow", 101:"MDN Web Docks", 102:"Javascript"},
      b = {0:{id:100, name:'Stack', lastname:'Overflow'}, 1:{id:101, name:'Web', lastname:'Docks'}},
      
      result = Object
        .keys(a)
        .reduce((acc, key) => {
          if(Object.values(b).some(({id}) => id == key))
            acc[key] = a[key]
          return acc
        }, {})
          
console.log(result)

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 read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

How can a method be called from a sibling component in Angular when it is bound through the <router-outlet>?

In my current project, I have implemented an application that utilizes HTTP calls to retrieve data from an API endpoint and then displays it on the screen. This app serves as a basic ToDo list where users can add items, view all items, delete items, and pe ...

Ways to extract the content from the textarea

Currently, I am working on a project that involves using CKEditor. Within the project, there is a panel with various properties used to create a tooltip. I decided to utilize CKEditor to insert content into the tooltip because it provides an excellent user ...

Browser now replacing attribute translate="yes" with translate="translate"

We have encountered an issue with a translation library that is affecting the functionality of our page. <html lang="en" class="notranslate translated-ltr"> <meta name="google" content="notranslate"> As ...

Incorporating JavaScript and Alpine.js to Monitor and Log Changes in Input Range Values

I have developed a basic app that logs the input range value to the console when the range input changes. Interestingly, it works flawlessly when I slide the slider left and right with my cursor. However, when I programmatically change the value using Ja ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Obtain the URL of the parent window from a modal dialog using JavaScript

What is the proper syntax for obtaining the URL (specifically, the PATH) of the parent window from a modal dialog box in Internet Explorer. I have attempted several variations such as: window.opener.document.location window.opener.location this.opener.do ...

How can one use jQuery to target elements that have names that are in an array format?

Is there a way to retrieve the values of these elements and send them as an array using ajax? <input type="checkbox" name="Broadcast[m]"/> Members <input type="checkbox" name="Broadcast[i]"/> IATA agencies <input type="checkbox" name="Bro ...

The onblur function is not being triggered

Recently, I encountered an issue while trying to invoke a JavaScript function onblur of a field. The main problems I faced were: 1) The popup inside the function call was triggered automatically during page load. 2) When attempting to access the functio ...

Filtering a table using jQuery based on the class or data attributes

Issue arises when selecting the first "Icon" shows "Not found", then opting for "Talisman" does not display. It should show "Not Found". Is this achievable? Add the classes f-Icon, f-Ring, f-Neck. Then search for the value by class. Select either "Icon R ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

The middleware attached to the router using router.use is not being executed

My NodeJS server application is up and running smoothly, thanks to the implementation of route protection I learned from an informative tutorial. After successfully obtaining a working token for login purposes, I decided to apply a middleware that would se ...

How to selectively display specific columns when outputting JSON to a dynamic HTML table?

I'm looking to output specific JSON data in an HTML table with JavaScript. The headers will remain the same, but the JSON content will vary. Currently, I have a working function that generates the entire table using JavaScript: <body> ...

The art of Vue JS displaying content

Learning how to make API requests using axios has greatly improved my ability to retrieve data in a client-side container and display it in my component template. It's been quite effective so far. Having worked with twig before, I can't help ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Is there a way to retrieve the href value from a modal window upon clicking the link?

When clicking on the a href, I am attempting to retrieve a value in my pop-up window. I am using magnificPopup JavaScript Below is the code for my a href tag and I want to fetch the "data-stream" value in the pop-up window. <a class="popup-with-zoom ...

Encountering the error "Uncaught reference error: $ is not defined" despite ensuring that scripts are loading in the correct order. However, the scripts work from the

Encountering an Issue: "Uncaught ReferenceError: $ is not defined" Whenever I try to utilize $('#someid') in my custom JavaScript code within an Electron app. All scripts are properly arranged in my HTML file: <script type="text/javascri ...

Creating a customizable React application with an extra environmental setting

I'm currently working on an app that requires some variations. While the core remains the same, I need to customize certain parts of the app such as color schemes and images. My inquiry is: Is it feasible to construct an app with a specified instance ...

Transmit information to Vue.js component

I am encountering an issue while attempting to transfer data from one component to another. Can someone provide assistance? Below is the code snippet: <template> <div class="q-pa-md" style="max-width: 900px"> <div v-if="fields.length" ...