Filter and select JavaScript objects based on the content of an array

I have a challenge filtering specific fields from a set of JavaScript objects:

   A= [{
      asset_bubble: 17,
      biodiversity_loss: 15,
      code: "CH",
      critical_information: 14,
      cyber_attacks: 19,
      data_fraud: 13,
      deflation: 4,
      energy: 18,
      extreme_weather: 12,
      change_adaptation: 9,
      infrastructure: 33
   },
   {
     asset_bubble: 4,
     biodiversity_loss: 7,
     code: "TZ"
     critical_information: 9,
     cyber_attacks: 9,
     data_fraud: 10,
     deflation: 3,
     energy: 1,
     extreme_weather: 2,
     change_adaptation: 7
     infrastructure: 3
}]

The goal is to filter out these fields using the following array:

array=["data_fraud","change_adaptation", "deflation","code"]

The desired result should be:

B= [{     code: "CH",
          data_fraud: 13,
          deflation: 4,
          change_adaptation: 9
       },
       {
         code: "TZ"
         data_fraud: 10,
         deflation: 3,
         change_adaptation: 7
    }]

My attempt involved using the map function as follows:

B = A.map(({ ...array }) => ({ ...array }))

However, this approach did not yield the expected output. I am aware that the map method should work but how can I correctly specify the fields to be filtered from the objects?

Answer №1

When inside the callback of Array.map, it is possible to map the values of the array variable to a pair of [key, item[key]]. By utilizing this 2d array, an object can be generated using Object.fromEntries in the following manner.

const A = [{
  asset_bubble: 17,
  biodiversity_loss: 15,
  code: "CH",
  critical_information: 14,
  cyber_attacks: 19,
  data_fraud: 13,
  deflation: 4,
  energy: 18,
  extreme_weather: 12,
  change_adaptation: 9,
  infrastructure: 33
}, {
  asset_bubble: 4,
  biodiversity_loss: 7,
  code: "TZ",
  critical_information: 9,
  cyber_attacks: 9,
  data_fraud: 10,
  deflation: 3,
  energy: 1,
  extreme_weather: 2,
  change_adaptation: 7,
  infrastructure: 3
}];

const array = ["data_fraud","change_adaptation", "deflation","code"];

const B = A.map((item) => (
  Object.fromEntries(array.map((key) => ([key, item[key]])))
));
console.log(B);

Answer №2

Presenting an alternative method leveraging the reduce function:

const C= [ {
      asset_bubble: 15,
      biodiversity_loss: 12,
      code: "JP",
      critical_information: 10,
      cyber_attacks: 13,
      data_fraud: 11,
      deflation: 3,
      energy: 16,
      extreme_weather: 9,
      change_adaptation: 7,
      infrastructure: 30
   },
   {
     asset_bubble: 6,
     biodiversity_loss: 9,
     code: "BR",
     critical_information: 8,
     cyber_attacks: 7,
     data_fraud: 8,
     deflation: 2,
     energy: 4,
     extreme_weather: 1,
     change_adaptation: 5,
     infrastructure: 5
}];

const array=["critical_information","deflation", "extreme_weather","code"];

const D = C.map(item => array.reduce((acc, key) => ({ ...acc, [key]: item[key]}), {}));

console.log(D);

Answer №3

NewArray = OriginalArray.map(({ property1, property2, property3, property4 }) => ({ property1, property2, property3, property4 }))

My suggestion would be to try this code snippet.

Answer №4

After reading Derek's response, I decided to create a useful function for filtering objects based on their keys:

function filterByKeys ( target, keyArr ) {
  return Object.fromEntries(
    Object.entries(target).filter(
      ([key,value]) => keyArr.includes(key)
    )
  )
}

Here is an example of how to use this function:

function filterBykeys ( target, keyList ) {
  return Object.fromEntries(
    Object.entries(target).filter(
      ([key,value]) => keyList.includes(key)
    )
  )
}

const data= [{
      asset_bubble: 17,
      biodiversity_loss: 15,
      code: "CH",
      critical_information: 14,
      cyber_attacks: 19,
      data_fraud: 13,
      deflation: 4,
      energy: 18,
      extreme_weather: 12,
      change_adaptation: 9,
      infrastructure: 33
   },
   {
     asset_bubble: 4,
     biodiversity_loss: 7,
     code: "TZ",
     critical_information: 9,
     cyber_attacks: 9,
     data_fraud: 10,
     deflation: 3,
     energy: 1,
     extreme_weather: 2,
     change_adaptation: 7,
     infrastructure: 3
}];

const arrays=["data_fraud","change_adaptation", "deflation","code"];

const result = data.map( obj => {
  return filterBykeys(obj, arrays);
});

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

The vacant array suddenly fills up with content once it is accessed

I encountered a strange scenario where the console.log indicated that the array was empty. However, upon inspection, I found 2 elements within it. This unexpected behavior prevented the component from rendering as it believed that conversations was empty. ...

The TypeScript find() method on an array are showing an error message that says, "There is no overload that matches this call

Issue Description I encountered a problem while using TypeScript's find() method for an array. Whenever I input a value, it does not work properly and displays an error message stating, "No overload matches this call". Code Snippet addOption(event: ...

Executing code within Vue js $set method's callback

For my v-for loop that generates a list of flights, I have implemented functionality where the user can click on a "flight details" button to send an AJAX request to the server and append new information to the results array. To update the view accordingly ...

Leveraging javascript to invoke a controller function within the MVC framework

My objective is to make a table row act as a link to redirect users to another view on my MVC website. Instead of using the conventional "Details" link generated by the table list, I want the entire row to serve as the link to the "Details" view. In order ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

The process of computing and graphing an array based on a specific field

After creating a straightforward mongoose query to extract an array of data and sorting it, I received the following response: [ { _id: 60c3dce8f27cc56bbcf20e94, steamID: '76561199105033642', displayName: 'username', L ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

Passing intricate data structure from Angular to SignalR

I am encountering an issue when trying to send a complex object to my SignalR hub. The JavaScript object I'm sending matches perfectly with my C# object, so theoretically everything should be functioning correctly. However, for some reason, my UpdateE ...

Go through every item in the list and update each element of the array with the outcome, doing so concurrently

Currently, I am struggling with implementing array asynchronous iteration functionality. I am working with the node-opcua library in Node.js. Specifically, I am using the function session.browse(nodeId, result). NodesTree = { "NodesTree":{ ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

Which option would be more beneficial for crafting a responsive UI: integrating a UI framework with three.js or solely relying on vanilla

In my quest to create a 3D editor using three.js, I find myself in uncharted territory. While I have a good grasp of JavaScript and three.js, my knowledge of web development and UI frameworks is lacking. Mrdoob's editor utilizes plain JavaScript for U ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Discovering the array item by its ID using Angular 2 with Typescript

Hey everyone, I'm currently working with asp.net mvc 5 and running into an issue. When attempting to retrieve an object by its id, it keeps returning undefined. The strange thing is that the objects display fine when checking console.log(this.vtypes). ...

Adjust the language of the submit and reset button text based on a variable

I'm facing a simple question but I'm stuck right now... and I was hoping someone could assist me. My issue is as follows: I need to switch the values of two buttons, reset and submit, from Greek to English and vice versa based on a variable retri ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

Enhancing the validation of multiple selects using jQuery

Here is what I have accomplished so far: JSFIDDLE My current goal is to: add the class "invalid" to the <select> if it was not selected in its respective row remove the "invalid" class if all 3 selects in the row are selected automatically submit ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Saved as a list in serialized form, with only a single record stored

I managed to retrieve a list containing an example of 1 ID: 12 History and stored it in the Customer model for mapping, placing it under customerList to consolidate it. However, when I attempted to serialize it, the output appeared as follows. If the cust ...