What is the most efficient way to transform an array of objects into a new array where I can selectively extract dynamic fields without relying on a traditional for loop

I am faced with a situation where I have an extensive array comprising approximately 1000 items. Depending on a certain condition, I only require specific fields from each object in the array to be extracted and mapped into a new, smaller array. The challenge here is that the required fields are dynamic, and I wish to avoid using a for loop within every iteration of the map function.

function extractFields(fieldsNeeded, data) {
  //Looking for a way to quickly extract specified fields from the data without utilizing a for loop
  return data.map((item) => {
    const newItem = {};
    for(const field of fieldsNeeded) {
      newItem[field] = item[field];
    }
    
    return newItem;
  }
}

let fieldsNeeded;
if(something) {
  fieldsNeeded = ['a', 'c'];
} else {
  fieldsNeeded = ['b', 'c'];
}

const data = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 }, { a: 10, b: 11, c: 12 } ];

const extractedData = extractFields(fieldsNeeded, data);

Answer №1

You can streamline your code by utilizing Object.fromEntries.

function extractData(fieldsRequired, dataSet) {
  return dataSet.map(item => Object.fromEntries(fieldsRequired.map(f => [f, item[f]])));
}
let fieldsRequired = ['name', 'age'];
const dataSet = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ];
console.log(extractData(fieldsRequired, dataSet));

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

Guide on organizing users into groups and filtering them using Firestore's reference field type

I currently manage a small group of employees with plans to expand in the future. To streamline operations, I am looking to implement a grouping feature that allows users to sort employees based on their assigned groups. Although I thought about using the ...

PHP seems to be resistant to receiving data from ajax requests

I am attempting to develop a drag and drop file upload feature without using a traditional form, utilizing JavaScript's FormData. However, I am encountering an issue where PHP does not seem to be receiving the uploaded file. Could there be some missin ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...

Enhance the efficiency of parsing JSON data

I am looking to extract and analyze the JSON data provided by this API (taken from their sample page): I have created a parsing method that takes quite some time (several seconds on my Galaxy A5) to process the extensive data: This is the approach I have ...

Compare and sync values across multiple data sources

Is there a simple way to synchronize data, specifically contacts, between an Android content provider and a JSON-based server? The challenge lies in the fact that Android uses cursors while the server is based on JSON. Additionally, the same values may ha ...

Any suggestions for a quicker method to manage state changes between OnMouseDown and OnMouseUp events in React?

I am attempting to create a window that can only be dragged from the top bar, similar to a GUI window. Currently, I have set up state updates based on OnMouseDown and OnMouseUp events on the top bar. However, I am experiencing slow updates as it seems to ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

Parse the Document Object Model (DOM) with the help of Selenium and generate an array data structure for each

Currently, I am tackling a task involving a table with three rows and seven columns. Each column houses an integer value, and the goal is to extract these values using Selenium to read the DOM. The desired outcome is to create an array containing all the ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

Show the outcome of the PHP code in an HTML table following a predetermined layout

Here is the content of my array: Array ( [0] => Array ( [mainProdName] => CellPhone [mainproductname] => Array ( [0] => Array ...

Slide your finger across the screen to reveal the next image

Seeking a guide or script that can help me showcase images within anchor tags and allow users to swipe left or right to view the next image. Preferably something compatible with JSON, jQuery Mobile, and includes a feature indicating the total number of i ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

Is it possible to pass a constant to another constant within Angular?

Is there a way to define a constant in Angular that depends on another constant being passed to it? See this example: angular .constant("names", ["Bob", "Jane"]) .constant("friends", ["names", getFriends]); function getFriends(names) { var friends ...

Experiencing issues with the fadeIn() and fadeOut() methods while constructing a slider using Object-Oriented Programming in JavaScript and jQuery

I'm currently trying to develop a slider using jQuery and JavaScript. I have successfully implemented the slide change functionality, but I am facing difficulties in smoothly adding fadeIn() and fadeOut() effects... No matter where I insert these eff ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

What is the most efficient way to iterate through a list of URLs containing JSON data, transform each one into a dataframe, and then store them in individual CSV files?

My goal is to fetch data from various URLs, transform each JSON dataset into a dataframe, and store the resulting data in tabular form such as CSV. I am currently experimenting with this code snippet. import requests url_list = ['https://www.chsli.or ...

Efficiently refine your search using the combination of checkboxes and dropdown menus simultaneously

I am currently in the process of creating a highly sortable and filterable image gallery that utilizes numerous tags. The inspiration for this project stems from a similar question on Stack Overflow regarding dropdown menus and checkboxes. You can view the ...

Having difficulty retrieving query or JSON keys from the Prometheus HTTP Server

I am trying to retrieve a specific metric called zcash_difficulty_gauge from the Prometheus HTTP Server, but I am encountering two issues: i) JSON data is not available ii) The request URL does not return just the desired metric, instead it returns the ent ...