Compare the array against the keys to filter the object

Currently, I have an object with keys that have multiple values.

Additionally, there is an array with a simple key check as follows: ["random", "three"].

My goal is to retrieve the mainData, but only with the object and the data that match the keys in the array, i.e. ["random", "three"].

Existing Code:

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    one: {
        name: "One Entity",
        date: "16/04/2022",
        startTime: "16:00",
        finishTime: "20:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

export default mainData;

Desired Output:

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

Attempted Solution:

let filterKey = 'random';
const result = Object.entries(mainData).filter(([k, v]) => k == filterKey);

This solution only works for a single search, not for searching through an array.

Answer №1

Transform the array into an entries array ([[key,val],[key,val],...]) and then use Object.fromEntries()

const mainData = {"random":{"name":"Random Entity","date":"05/04/2022","startTime":"19:00","finishTime":"00:00"},"one":{"name":"One Entity","date":"16/04/2022","startTime":"16:00","finishTime":"20:00"},"three":{"name":"Three Entity","date":"19/04/2022","startTime":"10:00","finishTime":"11:00"}}

const filters = ["random", "nope", "three"]

const result = Object.fromEntries(
  filters
    .filter(
      key => key in mainData // only include keys that are present in mainData
    ) 
    .map(
      key => [ key, mainData[key] ]
    )
)

console.log(result)
.as-console-wrapper { max-height: 100% !important; }

Answer №2

If you have specific keys to exclude, you can take this approach:

const mainData = { random: { name: "Random Entity", date: "05/04/2022", startTime: "19:00", finishTime: "00:00", }, one: { name: "One Entity", date: "16/04/2022", startTime: "16:00", finishTime: "20:00", }, three: { name: "Three Entity", date: "19/04/2022", startTime: "10:00", finishTime: "11:00" };

const {one, ...desiredData} = mainData;

console.log( desiredData );

Or, if you have specific keys to filter, you can use the map() function to extract the keys as [key, value] pairs from [key,mainData[key]], and then construct a new object from these key-value pairs using Object.fromEntries() like shown in the example below:

const mainData = { random: { name: "Random Entity", date: "05/04/2022", startTime: "19:00", finishTime: "00:00", }, one: { name: "One Entity", date: "16/04/2022", startTime: "16:00", finishTime: "20:00", }, three: { name: "Three Entity", date: "19/04/2022", startTime: "10:00", finishTime: "11:00" };

const desiredData = Object.fromEntries( ["random", "three"].map(f => [f, mainData[f]]) );

console.log( desiredData );

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

Error Encountered: Module Missing Following NPM Installation

I just started using Node and ran into an issue after setting up a new node project with NPM init. I tried installing lodash by running the command: npm install lodash --save However, the command resulted in the following error: npm ERR! code MODULE_NOT ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

Having trouble removing a cookie in express?

Seems pretty straightforward. In the /user/login route, I set a cookie as shown below: if (rememberMe) { console.log('Login will be remembered.'); res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...

Modifying Label text dynamically using jQuery on Click event

My website HTML contains the following code snippet: <script src="js/jquery.flexslider.js"></script> <script src="js/jquery.rings.js"></script> The contents of jquery.rings.js are as follows: $('input[type="image"]') ...

Issue encountered when sorting sequelize query by date in ascending sequence

My challenge is to arrange a sequelize query in ascending order by date. Specifically, I am focusing on sorting the results of the model: ExamScore (referred to as student_score). I've specified the column "updated_at" for ordering and the method of ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

Searching with Sequelize for an indirect relationship: How can it be done?

Within my database, there exists a relationship between Users and Roles. A User can have multiple Roles assigned to them. These Roles are connected to Activities in such a way that they can be associated with many different activities. This association all ...

Evaluating the use of promise in Angular using Jasmine testing

I'm currently troubleshooting whether a method with a promise is being properly called Below is the snippet of my controller code: app.controller('StoresListController', function ($scope, StoresService) { $scope.getStores = function ( ...

Can you explain the significance of the <%= %> HTML tag?

I've recently been tackling a project with Webpack. For those not familiar, Webpack is a bundler that combines all your files into one final product. One task I encountered was trying to insert one HTML file into another, similar to an import or requ ...

How can I implement a toggle button to display additional details for a specific row within a table created using React.js?

I'm currently working on a project using Next.js and have come across an unexpected issue. Upon reading a JSON file, I populate a table with the data retrieved from it. Each piece of information in the table has hidden details that should only be reve ...

"Facing an issue with my handleChange function not getting triggered in MaterialUI. Can anyone

Why isn't my handleChange function being invoked with the TextField component from Material UI? Even though I can input values in the text fields, the component's state is not updating. Here is the Auth component: const Auth = () => { cons ...

Is it true that Vue 3 + Inertia automatically removes event listeners upon component unmounting?

There is an event listener set up within the script setup block: <script setup> import {ref} from 'vue' const elementRef = ref(null) window.addEventListener('click', (event) => { if (!elementRef.value.contains(event.t ...

JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner: // module1.js let directory; export { directory }; Now, I am trying to access it in a separate module like so: // module2.js import { directory } from '../js/module1.js'; directo ...

Updating the content within the main body of the page rather than the sidebar in react-router v5

I have a question regarding the functioning of my sidebar and content. So, when I click on any item in the sidebar, the content changes accordingly. But what if I want to change the route directly from the content itself? That's where I'm facing ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

Understanding the extent of testing coverage in a project using karma and webpack

For my project, I am incorporating ES6 syntax and testing my code with Karma. While I have successfully set up testing, I encountered an issue with the coverage report. Instead of including the source code, the coverage report is highlighting spec file ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, https://i.sstatic.net/YJ1PI.png Created a function that retrieves values from local storage using forEach and displays them on the screen. https://i.sstatic.net/ ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...