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

How to set up perl-JSON on CentOS?

Whenever I attempt to execute a perl script on my CentOS 6 machine, I encounter the following error message: Can't find JSON.pm in @INC (@INC contains: /usr/local/lib/perl5/5.10.1/x86_64-linux-thread-multi /usr/local/lib/perl5/5.10.1 /usr/local/li ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Every time I restart the server with MEN stack, I encounter an error message stating "Cannot read property 'name' of null"

I am currently working on developing a campgrounds application based on Colt Steele's Udemy course "The Web Developer Bootcamp". Everything is going smoothly except for one issue I encountered. When I restart the server and directly access the URL wit ...

Create a three-dimensional tree array in Typescript/Javascript by transforming a flat array

Received data is structured as follows: const worldMap = [ { "name": "Germany", "parentId": null, "type": "Country", "value": "country:unique:key:1234", "id&qu ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

Removing an item from a parent array within a Vue.js component using Vue.js 2

Having a component with prop List, which is a list of input files. Each time an input is changed, another one is added. However, encountering strange behavior when attempting to delete. Link to JSFiddle removeAnother: function(item) { var vm = this; ...

Calculate the total of items in an array based on a different regular item in the same row using PHP

Here is a basic example of an array used in my PHP code. The original array is populated automatically by queries. I am trying to find a simple way to calculate the total of all "number" indexes in different rows with the same "fruit" index. For instance, ...

Populate dropdown list dynamically in Codeigniter using AJAX and jQuery

Although this question may appear to be a duplicate, none of the other answers provided have solved my issue. My query pertains to populating a dropdown using ajax/jquery. While I can successfully send and receive data in JSON format, it doesn't seem ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

Utilizing jQuery for cloning elements

I need to add functionality for adding and deleting rows in multiple tables on my website. Currently, I am doing this by directly inserting HTML code using jQuery, but it has become inefficient due to the number of tables I have. I am considering creating ...

Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, ...

Utilizing d3.csv to load CSV data into an nvd3 multiBar Chart demonstration (in JSON format)

I am attempting to recreate a nvd3.js multiBar Chart using my own .csv data. While I have come across similar questions in the past, none of them have provided a solution specific to my current issue. Some suggestions involve utilizing d3.entries, d3.nest, ...

What is the best way to declare a variable within a VueJS v-if condition without it being visible?

In my code, I have a specific template that is displayed when a certain condition is met using a v-if statement. In this template, I need to set a variable to N/A, but I am struggling with how to accomplish this simple task. <span v-if="se ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

What is the most effective method to extract an ID from a URL that is written in various formats?

Does anyone know of a reliable method to extract an ID from various URL formats using javascript or jquery? https://plus.google.com/115025207826515678661/posts https://plus.google.com/115025207826515678661/ https://plus.google.com/115025207826515678661 ht ...

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

creating an audio streaming application using child processes in nodejs

How can I effectively send a stream to a child process for streaming audio from a client to a server? I have successfully obtained the audio stream from a client. const ss = require('socket.io-stream'); const socketIo = require('socket.io& ...