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 selectively print the contents of a child window upon page load?

I've created a function that opens a child window and fills it with content using AJAX. function OpenWindow(){ jQuery.ajax({ type: 'POST', data: { //some fields }, url: 'getPageForPrint.php', su ...

Validating Users with OpenID in Vue.js

Utilizing the oidc-client in a basic VueJs project. The IDP server information is correctly configured in SecurityServices.js, with the following oidc config: var mgr = new Oidc.UserManager({ userStore: new Oidc.WebStorageStateStore(undefined), aut ...

Display or conceal a vue-strap spinner within a parent or child component

To ensure the spinner appears before a component mounts and hides after an AJAX request is complete, I am utilizing the yuche/vue-strap spinner. This spinner is positioned in the parent days.vue template immediately preceding the cycles.vue template. The ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Display a list with a set limit and an option to show more by clicking

I am currently struggling to develop a list of items that displays 3 items per row, and when the "show more" button is clicked, another 3 items should be displayed. My issue arises when using map and slice, as this method results in rendering 3 of the same ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

Logged in user currently viewing a Vue.js application on IIS

My current setup involves a Vue.js application hosted on an IIS server that communicates with a .Net Core web service also on the same server. The client site has Windows Authentication enabled, and I'm looking for the most efficient method to retriev ...

NG-model not visible to AngularJS Controller's filter

Finally, the code is working perfectly. It's a mystery to me. I created a custom filter to use with ng-repeat. The code is implemented within a Controller ... .controller('makeOrderController', function ($scope, $timeout, $ionicLoading) { ...

Acquiring radio button input in PHP

I have 2 radio buttons within a form, <label><input type="radio" onclick="this.form.submit()" name="shfaq<?php echo $i; ?>" value="1" id="radiobuttonsondazh_0" <?php if($result['live']==1) echo 'checked'; ?> /> ...

What is the best way to halt Keyframe Animation once users have logged in?

To enhance user engagement, I incorporated keyframe animation into my login icon on the website. The main objective is to capture the attention of visitors who are not registered users. However, once a user logs in, I intend for the keyframe animation to c ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Is there a way to display a message in a div container instead of using the alert box when there is a successful ajax response?

Hey there, I'm currently working on implementing error validation handling for a custom form that I've created. I'm looking to display the error messages in a designated div rather than using the standard browser alert box. Since I'm fa ...

Oops, looks like there's been an issue with the webpack build. It seems we're

I encountered an issue while building and running the development server using Webpack. My project is based on Vue.js, and I utilized vue-cli to generate it. Jest is used for testing, and running npm test poses no problems. However, when I run npm run bui ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

The conditional statement is malfunctioning when both dates are identical

If the deadline date is today or in the future, I want to display the deadline date. If the date has passed, I want to display the word 'Closed'. Below is the code I am using, which works except for when the deadline and today's date are th ...

Managing Vue StateWhether you're using Vuex or the

Is it possible to maintain the state of a Vue component so that when returning to it, the previous state is preserved? For instance: 1) I am on Page A, perform a search, results are displayed, I scroll down and select item 34. 2) Next, Page B opens with ...