Refining an object to only include keys that are present in a collection of objects

I've been racking my brain trying to find a more efficient way to achieve this without upsetting my eslint settings. Essentially, I'm attempting to remove keys from an object that do not exist in an array of objects. The code I currently have works fine but triggers eslint errors:

fieldData = recipeOutputFields(z, bundle);

  return promise.then((response) => response.json.response.map((item) => {
    const temp = item;

    temp.id = temp.customer_id;

    const diff = {};

    for (const [key, value] of Object.entries(temp)) {
      fieldData.some((el, val) => {
        if (el.key === key) {
          diff[key] = value;
        }
      });
    }

Here are some examples of the data I'm dealing with:

let theObjectINeedToRemoveKeysFrom = {
   key1: "test",
   key2: "test2",
   key3: "test",
   key4: "test",
}

let theArrayOfObjectsToFilterBy = [
    {
       key: "key1",
       type: "string",
    },
    {
       key: "key2",
       type: "string",
    },
    {
       key: "key4",
       type: "int",
    },
]

The desired output would be:

let expectedResult = {
   key1: "test",
   key2: "test2",
   key4: "test",
}

Any ideas on how to simplify my function to comply with eslint rules?

The ES Lint Errors: https://i.sstatic.net/6X9L2.png

Answer №1

One handy method to restructure the Object.entries array back into an object is by utilizing Object.fromEntries.

let temp = {
   key1: "test",
   key2: "test2",
   key3: "test",
   key4: "test",
};

let fieldData = [
    {
       key: "key1",
       type: "string",
    },
    {
       key: "key2",
       type: "string",
    },
    {
       key: "key4",
       type: "int",
    },
];

const diff = Object.fromEntries(
  Object.entries(temp).filter(([k, v]) => 
    fieldData.some(({key}) => k === key)
  )
);

console.log(diff);

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

Events triggered when a Jquery checkbox is toggled between checked and unchecked

I have written some HTML code that utilizes jQuery to manage checkboxes. <tr> <td> <div class="checkbox"> <label><input type="checkbox" id="checkbox2"></label> </div> </td> & ...

Is there a way to incorporate an 'input' type within an Icon Button component from Material UI in a React project?

Kindly review my code below. I have revamped it for clarity so you won't need to stress about important details! const test = () => { return ( <label > <input type='file' multiple style={{ display: &ap ...

Unable to view form data in .php file

How can I change the style of my "Submit" button when a user clicks on it to submit the form? The action attribute calls a PHP file, but the data doesn't show up until I remove the onSubmit attribute from the form. However, without it, I cannot use t ...

Error message: "Jackson @JsonCreator encountered an unrecognized property"

Trying to utilize Jackson for converting JSON into an instance of a class comprising simple Strings and another class using @JsonCreator. It appears that Jackson is unable to instantiate the other class. The issue arises when running this code during a te ...

Tips for seamlessly integrating an overlay into a different image

My current system is set up to overlay the image when you check the checkboxes. However, I'm facing an issue with positioning the image inside the computer screen so it's not right at the edge. Can anyone provide assistance with this? <html&g ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

Interactive Animation featuring Interactive Pop-up Boxes

I am facing an issue with the 'zoomIn' animation where the background: rgba(0, 0, 0, 0.5); is not present when the popup box appears. I want the background to be there from the start of the animation. Additionally, after clicking the Submit butt ...

Storing both strings and characters within a two-dimensional array in the C programming language

I am currently working on a project to create a DFA simulation program. The task involves taking user input and storing it in two separate arrays, which will be used as rows and columns. These arrays will then be used to create a 2D table of values. For e ...

Managing a variety of tasks within the handleBeforeInput function in DraftJS

I'm stuck in a tricky situation where I need to change a block to an ordered list when the user presses '1.'. Below is the code snippet that achieves this: _handleBeforeInput(str) { if (str !== '.') { return false; ...

Can a robust web application be developed using Kotlin in Node.js?

With the recent release of Kotlin 1.1, it is now possible to compile Kotlin projects into JavaScript as a target, allowing for full JavaScript compilation. Can a Node.js application, like an express webserver, be developed entirely using Kotlin code? As s ...

What is the reason behind requiring an additional click to hide an element on the screen?

Currently, I am attempting to use the jQuery .hide() method to conceal a specific element. The issue arises when the active radio button is chosen as the element fails to hide immediately. Strangely, after selecting the button, the element only hides once ...

Connecting Android devices to MS SQL Server

Currently, I am working on developing an online Android application that requires transferring four fields into MS SQL Server and inserting them as a row. To achieve this, I believe I will need a web service for the data transfer mechanism. My question i ...

`The activation of Bootstrap list items through embedded spans`

Apologies for the title, I couldn't think of a better way to explain my issue. I have a list-group and I want the buttons to display a specific color when active. However, it seems that the embedded spans are capturing the click event and not registe ...

The question of when to utilize userEvent.click versus fireEvent in React Testing Library

I'm currently diving into the world of React-Testing-Library. One question that I have is regarding testing mouse interaction on an element. I find myself a bit confused about whether to use userEvent.click(element) or fireEvent.click(element). Can b ...

Error: The variable "oppstart" has not been declared

How can I define the function oppstart? Could it be the reason why the calculator isn't working? When I click calculate, no result is displayed even though the rest of the code seems to be functioning correctly. <!DOCTYPE html> <html> &l ...

Tips for adjusting the default selection in a second dropdown menu

I have a dilemma with my two dropdown lists, "optionone" and "optiontwo". I am trying to alter the default selected value from "option value=3>3" to option value=3 selected>3 when the user selects 2 from the first dropdown list ("optionone"). <sc ...

Learn how to utilize the getElementByClassName method in JavaScript to insert checkboxes into two lists that share the same class name

I have a situation where I have two lists sharing the same class name. I need to dynamically create checkboxes in both of these lists based on XML data. My current dilemma lies in how to properly utilize getElementByClassName in JavaScript to add checkbox ...

Skip the "required" attribute in HTML forms for submission

Before submitting a form, I rely on the use of required for initial validation. <form action = "myform.php"> Foo: <input type = "text" name = "someField" required = "required"> <input type = "submit" value = "submit"> <input typ ...

Exploring a JSON object and dynamically populating FormData with values using jquery

I am working with a JSON object in jQuery that looks like this: userObj = { "loginId":"abc123", "class":"5", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5e5457565311584b4c0e0606087f58525e5653115c5052">[e ...

Lending a hand in deselecting a rule within the jcf-hidden add-on using Selenium

Currently, I am working on automating a website that utilizes the jcf-hidden class (a form of jQuery class) which hides the select element I want to access. By removing the display: block !important; property, I was able to successfully interact with the ...